Search code examples
c++stlc++14stdvectorpush-back

When i try to define this vector< pair< int , pair<int, int> > > vp(n)


There's in output Give me 0 0

#include <bits/stdc++.h>
#define fsv(i , n)  for(int i = 0 ; i < n ; ++i)
using namespace std;

int main()
{
 int n ;
 cin >> n ;
 vector< pair< int , pair<int, int> > > vp(n);
 vector <int> v(n) ;

 fsv(i , v.size())cin >> v[i];

  for(int i = 0 ; i < n ; ++i){
     for(int j = i+1 ; j < n-1 ; ++j){
        vp.push_back(make_pair(abs(v[i]-v[j]) , make_pair(i,j)));
     }
  }
 sort(vp.begin() , vp.end());

 cout << vp[0].second.first << " " << vp[0].second.second;

}

this code related by code forces problem , i know that there's other ways ... but i'm asking this is proper way to access elements like that ?! http://codeforces.com/contest/34/problem/A


Solution

  • The problem is that

    vector< pair< int , pair<int, int> > > vp(n);
    // ......................................^^^  n initial elements
    

    initialize a vector with n elements and with push_back() you add other n elements`.

    After sorting v, the v[0] element is (I suppose) one of the initials n.

    You should create an empty vector

    vector< pair< int , pair<int, int> > > vp;
    // ....................................^^  no more initial elements; empy!
    

    and, just to speed up and avoid a superfluous relocations, reserve n as size (but ins't necessary)

    vp.reserve(n);
    

    before pushing back n elements.

    Off Topic suggestion: please, avoid including a not-standard header as

    #include <bits/stdc++.h>