tags:

views:

61

answers:

4

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++.

+2  A: 

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;
fabrizioM
They are an vector of objects. I want to be able to change the items in the list without always having to have use list.at(i).x = 10, since its very long.
Kira
+8  A: 
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.

James McNellis
+4  A: 

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).

Nikolai N Fetissov
A: 

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.

Cedric H.