Search code examples
vectorstd-pair

Printing vector of pair in C++


Here is the code to print the value in vector of pair

But why does it print the output mentioned below..?

   #include<bits/stdc++.h>
   using namespace std; 
   int main()
   {
      vector<pair<int,int>>vec(3,pair<int,int>()); // declaring the vector of pair.
      for(auto x: vec)
        x=make_pair(1,2);                          // looping through it to insert values
      for(auto x:vec)
        cout<<x.first<<" "<<x.second<<endl;        // printing it

      return 0;
   }

Output :

0 0 
0 0
0 0    

Expected :

1 2
1 2
1 2

Solution

  • In your first for-loop you iterate through your vector "by value", meaning you copy the elements to auto x and afterwards set x to {1,2}, this does not change your original vector. To actually change your vector you have to iterate through it by reference:

    for(auto& x: vec)
      x=make_pair(1,2);