sudo
sudo

Reputation: 329

Changing things from a vector

What is the easiest way to take something out of an vector and changes its values? This isn't working the way I expected.

for(int i = 0; i < list.size(); i++) {
someType s = list.at(i);
s.x = 10;
s.y = 20;
s.z = 30;
}

However, when I go to print out the x,y,z of that someType s, it doesn't give me what I expect. Sorry I am mixing up Java and C++.

Upvotes: 1

Views: 150

Answers (4)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84229

There's no "ArrayList" in standard C++ library. I'm guessing you are using std::vector, std::vector<someType> to be exact.

STL containers store objects by value. The first line within that loop body invokes someType's copy constructor, so you end up with a copy of the object. That copy is automatically allocated, i.e. it's on the stack. You update the copy and then it goes out of scope and is destructed at the end of the iteration. The original object held in the vector is unchanged.

Edit:

And of course I forgot to make the final point - use a reference (see James' answer, which you should probably accept).

Upvotes: 4

Cedric H.
Cedric H.

Reputation: 8298

You are copying the values; each object is copied using its [default] copy-constructor.

I you want to refer to the elements of the list more easily, you should use references:

for(int i = 0; i < list.size(); i++) {
someType& s = list.at(i);
//      ^ This is a reference
s.x = 10;
s.y = 20;
s.z = 30;
}

You can think about this reference just as an "alias" to an element of the list.

Upvotes: 0

fabmilo
fabmilo

Reputation: 48330

Most probably you are copying the values. How is defined the list ? a list of objects or a list of pointers to objects? Make sure to use the & as "reference" to the list item.

T& s = list.at(i);
s.x = 0;
s.y = 1;

Upvotes: 2

James McNellis
James McNellis

Reputation: 355267

someType s = list.at(i);

You are making a copy of the element at index i. In C++, if you want a reference to something, you need to explicitly state that you want a reference:

someType& s = list.at(i);
     // ^ I'm a reference

As it is written now, you only manipulate the copy that you make, not the object in the container.

Upvotes: 9

Related Questions