简体   繁体   English

如何在C ++中使用迭代器更改vector中每个elmement的值

[英]How to change the value of each elmement in vector using iterator in C++

I wrote the following program to initialize a vector of Person . 我编写了以下程序来初始化Personvector But the id of the Person objects does not change. 但是Person对象的id不会更改。 This really confuses me. 这真的让我感到困惑。 Can somebody give me an explanation? 有人可以给我一个解释吗?

#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;
}

with person.h like this 像这样与person.h

#include <string>

class Person
{
  public:
    int id;
    std::string name;
    Person(int d);
};

In this loop you need to iterate by reference or you will be assigning to the id of a copy of the Person in the vector, not the actual Person in the vector. 在此循环中,您需要通过引用进行迭代,否则您将在向量中分配给Person的副本的ID,而不是向量中的实际Person。

for(Person& person : *pv)
{
    person.id = i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM