c++ - std::sort on a vector of Objects containing Objects* pointers -



c++ - std::sort on a vector of Objects containing Objects* pointers -

let's define next struct:

struct dockpose { complex* pose; int cluster; struct dockpose* dp; float distance; int density; }; typedef struct dockpose dockpose;

then, declare vector sorted density value using std::sort() function. after phone call std::sort, dockpose* dp pointers still point same dockpose instance pointing before? if not, can sure dp pointers points same dockpose pointing before sorting (if there can do) ?

yes, pointers still point same instance. may not want. when phone call std::sort on vector, not alter location of instances (that's not thing can in c++). swaps values each other. improve explained simplified example. take struct:

struct foo { int x; foo* buddy; }; bool operator<(foo const& lhs, foo const& rhs) { homecoming lhs.x < rhs.x; }

now, lets create vector of these, decreasing x values, , each 1 having pointer 1 comes after (and lastly having pointer first):

std::vector<foo> vec(5); (int = 0; < 5; ++i) { vec[i].x = 4 - i; vec[i].buddy = &vec[(i + 1) % 5]; }

now, if sort vector, going reverse. instances don't alter location. instead, values alter such first 1 has lowest x value, , increases there. now, pointer fellow member changes along x value.

so take, example, vec[0], had x value of 4, , pointer vec[1] (which has x value of 3). after sort, values end in lastly element, vec[4]. vec[4] have x value of 4, , pointer vec[1] (which, after sort, has x value of 1).

so, before sort, element x value 4, had pointer element x value of 3. after sort, element x value of 4 has pointer element x value of 1. uncertainty wanted.

since interested in identity of instances, not values, should using std::vector<std::unique_ptr<dockpose>>. foo example, this:

std::vector<std::unique_ptr<foo>> vec; (int = 0; < 5; ++i) vec.emplace_back(new foo); (int = 0; < 5; ++i) { vec[i]->x = 4 - i; vec[i]->buddy = vec[(i + 1) % 5].get(); }

note when this, need utilize different comparing function. 1 compares dereferenced pointers, rather pointers themselves.

c++ sorting vector

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -