0

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?

nishant_boro
  • 374
  • 1
  • 2
  • 8
  • 3
    How is the result wrong? What do you expect? What do you get? How do those differ? – François Andrieux Mar 14 '18 at 15:30
  • 2
    You create a vector of `n` elements, then add `n` more, then print the first `n` elements. The ones you `push_back` come after the ones you print. You likely want to start with an empty vector. – François Andrieux Mar 14 '18 at 15:31

1 Answers1

0

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));
}
seccpur
  • 4,996
  • 2
  • 13
  • 21