I have a misunderstanding of how does work references, STL containers and Objects.
I previously look for using references in an STL container, but it seems that STL containers are "objects that store objects". But if I want to store objects and modifying them in the container, how can i do it ?
I pasted a small snipet of code illustrating my issue.
class MyObject {
public :
int value;
MyObject(const MyObject& right) : value(right.value) {}
MyObject(int _value) : value(_value) {}
bool operator< (const MyObject& right) const {
return value < right.value;
}
void display() const {
cout << "(" << value << ") ";
}
};
And in the main section
cout << "Creating ... " << endl;
set<MyObject> oset;
for (int i = 0 ; i < 10 ; i++) {
MyObject o(rand() % 1000);
oset.insert(o);
}
cout << endl;
cout << "Display before ... " << endl;
for (MyObject o : oset) o.display();
cout << endl;
cout << "Incrementing ... " << endl;
for (MyObject o : oset) o.value += 1000;
cout << "Display after ... " << endl;
for (MyObject o : oset) o.display();
cout << endl;
Since the container does not use references, the incrementation is applied on copies and not the objects.
I tried to use '&' insided the loop i.e.
for (MyObject& o : oset) o.value += 1000;
but I had the following error :
error: invalid initialization of reference of type ‘MyObject&’ from expression of type ‘const MyObject’