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