开发者

Changing things from a vector

开发者 https://www.devze.com 2023-01-23 02:19 出处:网络
What is the easiest way to take something out of an vector and changes its values? This isn\'t working the way I expected.

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


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.


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


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;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消