C++ 在指向std::set的指针上插入
在有指针和无指针的集合上插入值的行为不同。 这个代码有什么问题? 第一个for循环是使用指针在集合上插入,第二个没有指针。 但除此之外,其他一切都是一样的C++ 在指向std::set的指针上插入,c++,stdset,C++,Stdset,在有指针和无指针的集合上插入值的行为不同。 这个代码有什么问题? 第一个for循环是使用指针在集合上插入,第二个没有指针。 但除此之外,其他一切都是一样的 #include <iostream> #include <set> using namespace std; typedef struct{ int local; int global; }Node; Node CreateNode(int global, int local) { Nod
#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;
}
问题可能是compare()函数不返回比较结果。尝试:
bool compare(Node a, Node b){
return a.global < b.global;
}
bool比较(节点a、节点b){
返回a.global
<>未来可以考虑传递墙参数对GCC(4.7.3)的影响。编译器将警告您此类错误。默认情况下,clang(3.2)会发出警告,VC++(2010)会报告错误。您在哪个平台上工作?我在g++4.7.3中看到了理智的行为。?将代码逐字复制到ideone。com@WhozCraig我也得到了10和10作为答案,所以看起来很好…我错过了比较中的回报。试试看,我真蠢。它在添加return后工作,但对于非指针和指针,它都工作,这仍然很奇怪。知道为什么会这样吗?@mvairavan-如果函数没有返回期望返回的值,则行为是
未定义的
。
bool compare(Node a, Node b){
return a.global < b.global;
}