STL列表迭代器不会更新我的对象 [英] STL list iterator won't update my object
问题描述
我使用list iterator将Pets的所有年龄设置为1,但更改不会在for循环之外持续:
I am using a list iterator to set all the ages of the Pets to 1 but the change won't persist outside the for loop:
#include <iostream>
#include <stdio.h>
#include <list>
using namespace std;
class Pet{
public:
int age;
};
class Person{
public:
list<Pet> pets;
};
int main(int argc, char **argv) {
Person bob;
Pet p1;
p1.age = 0;
bob.pets.push_back(p1);
cout << "Start with: "<<p1.age << endl;
std::list<Pet>::iterator itPet;
for (itPet = bob.pets.begin(); itPet != bob.pets.end(); ++itPet) {
Pet p = (*itPet);
p.age = 1;
cout << "Right after setting to 1: "<<p.age << endl;
}
cout << "After the for loop: "<<p1.age << endl;
return 0;
}
输出:
Start with: 0
Right after setting to 1: 1
After the for loop: 0
为什么p1没有更新?如果不是p1又更新了什么?
Why is p1 not updated? And what has been updated if not p1?
谢谢!
推荐答案
您只需修改副本:声明
Pet p = (*itPet);
将 * itPet
的值复制到 p
然后会更新。您可以使用以下代码验证迭代器使用的对象:
copies the value of *itPet
to p
which then gets updated. You can verify that the object used by the iterator by using this code:
p.age = 1;
cout << "Right after setting to 1: p.age="<<p.age << " itPet->age=" << itPet->age << '\n';
您想给我们一个参考:
Pet& p = *itPet;
用于验证列表中的对象是否已更改的方法不起作用但是:标准C ++库容器会复制插入的对象,并且不会保留对原始对象的引用。也就是说, p1
不会被更改,但列表中的元素会被更改:
The approach you are using to verify whether the objects in the list are changed doesn't work, either, though: the standard C++ library containers make a copy of the objects inserted and don't keep a reference to the original object. That is, p1
won't be changed but the element in the list is changed:
for (std::list<Pet>::const_iterator it(bob.pets.begin()), end(bob.pets.end());
it != end; ++it) {
std::cout << "list after change: " << it->age << '\n';
}
这篇关于STL列表迭代器不会更新我的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!