如何为已显式定义了比较函数的集合定义迭代器

How to define iterator for a set whose compare function I have defined explicitly?

本文关键字:定义 函数 比较 集合 迭代器      更新时间:2023-10-16

Set I have defined:

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*>}'
)

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

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

去掉这些,错误就会消失。

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

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

或者更好,如果可能的话,使用基于范围的for循环:

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