gpt4 book ai didi

c++ - 如何为已明确定义其比较函数的集合定义迭代器?

转载 作者:行者123 更新时间:2023-11-30 01:42:45 25 4
gpt4 key购买 nike

我定义的集合:

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) { ...

关于c++ - 如何为已明确定义其比较函数的集合定义迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39079759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com