【问题标题】:How to define iterator for a set whose compare function I have defined explicitly?如何为我明确定义了比较函数的集合定义迭代器?
【发布时间】:2016-08-22 12:37:15
【问题描述】:

我已经定义的集合:

set < Node*, bool (*)(Node *, Node *) > visited(Node::compare);    

比较函数定义:

struct Node {
    int config[8][8];
    static int n;
    Node *parent;
    static bool compare(Node *, Node *);
};    
int Node::n = 0;    

bool Node::compare(Node *a, Node *b) {
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            if( a->config[i][j] != b->config[i][j]) {
                return true;
            }
        }
    }
    return false;
}      

现在,我想在代码的某个点迭代它。但是下面的代码不起作用。

for(set <Node*, bool (*)(Node*, Node*)>::iterator itt = visited.begin();      itt != visited.end(); itt++) {    
    delete (*it);    
}

错误是:

error: no match for 'operator<'
(operand types are
    'std::set<Node*, bool (*)(Node*, Node*)>::iterator {aka std::_Rb_tree_const_iterator<Node*>}'
     and
    'std::set<Node*, bool (*)(Node*, Node*)>::iterator {aka std::_Rb_tree_const_iterator<Node*>}'
)

【问题讨论】:

  • 奇怪的是,使用for(auto&amp; iter : container)会发生什么?? - 不使用 C++11?
  • 错字:您添加了一个额外的()。你需要set &lt;Node*, bool (*)(Node*, Node*)&gt;::iterator。但只需使用auto。
  • 除了提到的错字@juanchopanza,您的for 循环中的条件不太正确。使用itt != visited.end() 而不是itt &lt; visited.end()
  • 如果您没有支持 C++11 的编译器并且不能使用 auto 或 range-for 进行类型推断,那么请考虑使用类型别名(即 typedef ) 为集合。更容易将所有“模板”内容只键入一次,然后为它使用一个好听的名称。

标签: c++ stl iterator set


【解决方案1】:

您的模板声明中有一堆错误的括号:

set<Node*, bool(*)(Node*, Node*)())>::iterator
                                ^^^

删除这些,错误就会消失。

除此之外,我强烈建议改用auto:

for (auto it = visited.begin(); it != visited.end(); ++it) { ...

如果可能的话,甚至更好的是,使用基于范围的 for 循环:

for (const auto& node : visited) { ...

【讨论】:

  • 是的,我删除了那些多余的括号。这是格式错误。
  • 但是,使用 auto 会出错:'it' 没有命名类型。
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 2019-02-20
  • 2014-12-02
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
相关资源
最近更新 更多