c++ - Sorting a vector of pointers using std::sort resulting in jumbled addresses? -


i'm writing function sort vector of class pointers. before sorting, vector contains following pointers:

{0x784170, 0x7841a0, 0x784050, 0x783f10, 0x783f40, 0x7832a0, 0x7832d0, 0x7831a0, 0x7831d0, 0x783080, 0x7830b0, 0x782f40, 0x782f70, 0x7827c0, 0x7827f0} 

after sorting, contains these:

{0x3141954a38, 0x3141954a38, 0x784050, 0x783f10, 0x783f40, 0x7832a0, 0x7832d0, 0x7831a0, 0x7831d0, 0x783080, 0x7830b0, 0x782f40, 0x782f70, 0x7827c0, 0x80} 

the following code:

bool dnodecomparator(dnode* x, dnode* y) { return x->getdfn() < y->getdfn(); }  void sortfunction(){     vector<dnode*> operations = applicationgraph.getoperations();     std::sort(myvector.begin(), myvector.end(), mycomparator); }  class dgraph {     private:         vector<dnode*> nodes;      public:         vector<dnode*> getoperations(){return nodes;} }; 

the code runs on dependency graph contains vector of dnode* objects. i'm returning vector of pointers , sorting each node it's dfn field. dnode class contains operation* objects, boolean flags, , int value computing depth first numbering of dependency graph. addresses shown in first line result of gdb print operations call right before std::sort call. addresses in second line print operations call right after std::sort.

i've tried couple more debugging steps, still can't reconcile error. returning vector of dnode* creates desired copy of vector stored in separate address, modifying new vector (such adding more dnodes) not modify actual vector in graph class. shouldn't cause problems vector still contains each dnode*.

here working example based on comparator.

#include <algorithm> #include <iostream> #include <vector>  struct obj {   int id;   int getid() {     return id; }   obj(int i) : id(i) {} };  bool mycomparator(obj* a, obj* b) {   return a->getid() < b->getid(); }  int main(int, char* []) {   std::vector<obj*> myvector;    (int = 0; < 4; ++i) {     myvector.push_back(new obj(i)); }    std::random_shuffle(myvector.begin(), myvector.end());    (std::vector<obj*>::iterator = myvector.begin();        < myvector.end(); ++i) {     std::cout << (*i) << " " << (*i)->getid() << " "; }    std::cout << std::endl;   std::sort(myvector.begin(), myvector.end(), mycomparator);    (std::vector<obj*>::iterator = myvector.begin();        < myvector.end(); ++i) {     std::cout << (*i) << " " << (*i)->getid() << " "; }    std::cout << std::endl;   return 0; } 

ouput

0x80010308 2 0x80010318 1 0x80010328 3 0x800102f8 0 0x800102f8 0 0x80010318 1 0x80010308 2 0x80010328 3 

how code different this?


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -