Reputation: 3388
I have a vector of People object stored somewhere
std::vector<People> people;
Now I find some special people and get their reference, then get their pointer and store in a vector:
std::vector<People*> newlist;
The way I get this list:
People& specialPeople = getSomeSpecialGuyFrom(people); // get a referece
newlist.push_back(&specialPeople);
// New I sort the newlist by some property, assuming it's not empty:
std::nth_element(newlist.begin(),
newlist.begin() + 1,
newlist.end(),
[](const People* p1,
const People* p1) {
return p1->reputation > p2->reputation;
});
newlist[0]->name = "Best one";
Note that I keep the original people vector not changed. The point of storing pointers is to make the sort cheap. Now my question is, the last assignment, is it changing the original people vector? From the way I read the code it should, but in practice I see opposite result? Sorry I can't use the real code here...
Upvotes: 1
Views: 58
Reputation: 238311
the last assignment, is it changing the original people vector?
It depends.
Answer is yes if and only if getSomeSpecialGuyFrom
returns a reference to an object in the original people vector and the reference/pointer hasn't been invalidated.
Upvotes: 2