[英]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.