Search code examples
c++stringpush-back

Pushing back into a vector of pairs from cin giving wrong results


So i am trying to build a vector and then push back pair items into it. The code goes like this:

int main() 
{
    int n;
    cin >> n;
    vector<pair<int,string>> o(n,make_pair(0," "));

    for(int a0 = 0; a0 < n; a0++)
    {
        int x;
        string s;
        cin>>x>>s;
        o.push_back(make_pair(x,s));
    }
    for(int i=0;i<n;++i)
        cout<<o[i].first;

    return 0;
}

But the resultant vector is showing wrong results. So what is wrong here?. Can someone help me out?


Solution

  • Use only this vector<pair<int, string>> o; Yours will end up with 2n elements in the vector or you can

    int n;
    cin >> n;
    vector<pair<int, string>> o (n, make_pair(0, " "));
    
    for (int a0 = 0; a0 < n; a0++)
    {
        int x;
        string s;
        cin >> x >> s;
    
        auto& it = o.at(a0);
        (it.first) = x;
        it.second = s;
        //o.push_back(make_pair(x, s));
    }