Search code examples
c++stdset

inserting on a pointer to std::set


Inserting values on Set with and without pointer behaves differently. What is wrong with this code? The first for loop is insertion on set using pointer and the second is without pointer. But apart from that everything else is exactly same.

#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;
}

Output:

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

Solution

  • The problem may be the compare() function which doesn't return the result of comparison. Try:

    bool compare(Node a, Node b){
        return a.global < b.global;
    }
    

    In the future you may consider passing -Wall parameter to GCC (4.7.3). The compiler will warn you about such mistakes. clang (3.2) warns about them by default, VC++ (2010) reports an error.