[英]How to change the value of each elmement in vector using iterator in C++
我编写了以下程序来初始化Person
的vector
。 但是Person
对象的id
不会更改。 这真的让我感到困惑。 有人可以给我一个解释吗?
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
using namespace std;
int main()
{
vector<Person>* pv = new vector<Person>(5,Person(0));
int i = 0;
for(Person person : *pv)
{
person.id = i++;
}
for(Person person : *pv)
{
cout<< person.id << endl;
}
return 0;
}
像这样与person.h
#include <string>
class Person
{
public:
int id;
std::string name;
Person(int d);
};
在此循环中,您需要通过引用进行迭代,否则您将在向量中分配给Person的副本的ID,而不是向量中的实际Person。
for(Person& person : *pv)
{
person.id = i++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.