在带有和不带指针的Set上插入值的行为有所不同。 这段代码有什么问题? 第一个for循环是使用指针插入set,第二个是没有指针。 但除此之外,其他一切都完全相同。
#include <iostream>
#include <set>
using namespace std;
typedef struct{
int local;
int global;
}Node;
Node CreateNode(int global, int local) {
Node n; n.local=local; n.global=global;
return(n);
}
bool compare(Node a, Node b){
a.global < b.global;
}
int main()
{
std::pair<std::set<Node>::iterator,bool> itr;
set<Node,bool(*)(Node,Node)> *graph_set_pointer = new set<Node,bool(*)(Node,Node)>(compare);
for(int i=10;i>0;--i){
itr = graph_set_pointer->insert(CreateNode(i,i));
cout << "global = " << i << " local = " << i ;
cout << " inserted_global = " << (*itr.first).global << endl;
}
cout << "Number of items in pointer set = " << graph_set_pointer->size() << "\n\n";
set<Node,bool(*)(Node,Node)> graph_set_object(compare);
for(int i=10;i>0;--i){
itr = graph_set_object.insert(CreateNode(i,i));
cout << "global = " << i << " local = " << i ;
cout << " inserted_global = " << (*itr.first).global << endl;
}
cout << "Number of items in non pointer set = " << graph_set_object.size() <<"\n";
delete graph_set_pointer;
return 0;
}
输出:
global = 10 local = 10 inserted_global = 10
global = 9 local = 9 inserted_global = 9
global = 8 local = 8 inserted_global = 8
global = 7 local = 7 inserted_global = 7
global = 6 local = 6 inserted_global = 7
global = 5 local = 5 inserted_global = 7
global = 4 local = 4 inserted_global = 7
global = 3 local = 3 inserted_global = 7
global = 2 local = 2 inserted_global = 7
global = 1 local = 1 inserted_global = 7
Number of items in pointer set = 4
global = 10 local = 10 inserted_global = 10
global = 9 local = 9 inserted_global = 9
global = 8 local = 8 inserted_global = 8
global = 7 local = 7 inserted_global = 7
global = 6 local = 6 inserted_global = 6
global = 5 local = 5 inserted_global = 5
global = 4 local = 4 inserted_global = 4
global = 3 local = 3 inserted_global = 3
global = 2 local = 2 inserted_global = 2
global = 1 local = 1 inserted_global = 1
Number of items in non pointer set = 10
答案 0 :(得分:0)
问题可能是compare()函数,它不返回比较结果。尝试:
bool compare(Node a, Node b){
return a.global < b.global;
}
将来您可以考虑将-Wall参数传递给GCC(4.7.3)。编译器会警告你这些错误。 clang(3.2)默认警告它们,VC ++(2010)报告错误。