我正在使用列表迭代器将所有宠物的年龄设置为 1,但更改不会在 for 循环之外持续存在:
#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,更新了什么?
谢谢!
最佳答案
你只需修改一个拷贝:声明
Pet p = (*itPet);
将 *itPet
的值复制到 p
然后更新。您可以使用以下代码验证迭代器使用的对象:
p.age = 1;
cout << "Right after setting to 1: p.age="<<p.age << " itPet->age=" << itPet->age << '\n';
您想给我们一个引用:
Pet& p = *itPet;
您用于验证列表中的对象是否已更改的方法也不起作用:标准 C++ 库容器制作插入对象的拷贝,并且不保留对原始对象的引用.也就是说,p1
不会改变,但列表中的元素会改变:
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';
}
关于c++ - STL 列表迭代器不会更新我的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20767634/