【问题标题】:Error with going through map elements with a class pointer as values使用类指针作为值遍历映射元素时出错
【发布时间】:2020-12-29 14:41:24
【问题描述】:

我有一个类用于尝试

class Node {
public:
    map<char,Node*> node;
    bool flag = false;
};

int main(){
    Node table;
    for(auto x: table){}
    return 0;
}

我正在尝试遍历它的元素,但我不断收到错误

我检查了堆栈中的解决方案并尝试使用迭代器映射方法:

error: 'class Node' has no member named 'begin'
for (it = table->begin(); it != table->end(); it++){
                ^~~~~
error: 'class Node' has no member named 'end'
    for (it = table->begin(); it != table->end(); it++){

也尝试使用for循环,得到了类似的错误:

error: 'begin' was not declared in this scope
for(auto x: table){
            ^~~~

如何以其他方式遍历元素或如何修复这些错误?

【问题讨论】:

  • table的类型是什么?
  • 表的类型是(Node*)
  • 嗨,欢迎来到 StackOverflow!请创建一个Minimal Reproducible Example,准确显示您正在编写的内容以及您遇到的错误。
  • 当我改变它时不会改变
  • @KaiserKatze 这是一个可疑的建议,因为标准容器不是为多态而设计的。我可以工作,但你必须提防对象切片。此外,标准容器没有 virtual 析构函数,因此您还必须小心存储派生类型的方式。见Is it okay to inherit implementation from STL containers, rather than delegate?。不建议从标准容器派生而不提及警告。

标签: c++ dictionary


【解决方案1】:

Node 不是可迭代的类。这只是一个普通班级,恰好有一个std::map 作为成员。您想要的是访问 `Node:

中的 map 对象

for (auto x : table-&gt;node)

此外,在您向我们展示的代码中,table 从未初始化。我假设在你的真实代码中,它是,但如果不是,也修复它。您可以使用new Node 创建对象,或者将其声明为值而不是指针:Node table;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多