dimanche 26 septembre 2021

Strange behavior of std::pair [duplicate]

Absolutely don't understand, why this code:

vector<int>v={1,2,3,4,5};
vector<pair<int,int>> pairs;
pairs.push_back(make_pair(1, 1));
for (auto el:v) {
   for (auto p:pairs) {
      pairs[0].second++;
      cout<<p.second;
   }
}

prints "12345", and this code:

vector<int>v={1,2,3,4,5};
vector<pair<int,int>> pairs;
pairs.push_back(make_pair(1, 1));
for (auto el:v) {
   for (auto p:pairs) {
      p.second++;
      cout<<p.second;
   }
}

prints "22222" (The only difference is in changing pairs[0].second++ on p.second++)

Aucun commentaire:

Enregistrer un commentaire