Search code examples
c++vectorstlkey-value

Why I can't insert the pair value like this? v.push_back(vector<pair<int,string> >({1,"A"}));?


I have written this code, and want to insert a value in the vector<vector> like this:

v.push_back(vector<pair<int,string> >({1,"A"}));

But it shows an error. I want to know why this is not possible.

Inserting an empty value works:

v.push_back(vector<pair<int,string> >({}));

Here is the code:

#include<bits/stdc++.h>
using namespace std;

void printVec(vector<pair<int,string> > &v){
    cout << "Size: " << v.size() << endl;
    for(int i=0; i<v.size(); i++)
    {
        cout << v[i].first << " " << v[i].second << endl;
    }
}

int main()
{
    vector<vector<pair<int,string> > > v;

    int N;
    cin >> N;
    for(int i=0; i<N; i++)
    {
        int n;
        cin >> n;
        v.push_back(vector<pair<int,string> >({}));
        for(int j=0; j<n; j++)
        {
            int x;
            string s;
            cin >> x >>s;
            v[i].push_back({x,s});
        }
    }

    v.push_back(vector<pair<int,string> >({})); // UNABLE TO STORE A PAIR AT THE END. ONLY CAN ADD EMPTY PAIR. DON'T KNOW WHY??
    // v.push_back({}); // USING ANY OF THEM

    for(int i=0; i<v.size(); i++)
    {
        printVec(v[i]);
    }
}

Solution

  • Here you are pushing a pair instead of a vector of pairs.

    v.push_back(vector<pair<int,string> >({1,"A"}));
    

    This works because it considers ({}) as an empty vector of pairs. `

    v.push_back(vector<pair<int,string> >({}));`
    

    Although the following will work:

    vector<pair<int,string> > temp;
    temp.push_back({1, "Hi"});
    v.push_back(vector<pair<int,string> >({temp}));