mercredi 1 juillet 2015

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

I wrote the follow program to initialize a vector of Person. But the id of the person objects does not change. This really confuse 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 #include

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

Aucun commentaire:

Enregistrer un commentaire