0

I am having difficulty pushing two integers as a pair in vector. I'd like to know where it went wrong. Thank you!

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
    vector <pair<int,int>> vec;
    int s,n; cin>>s>>n;

    for(int i=0;i<n;i++){
        int in1,in2; cin>>in1>>in2;
        vec[i].push_back(make_pair(in1,in2));
    }
    sort(vec.begin(),vec.end());

    int checker=1;
    for(int i=0;i<n;i++){
        if(s<=vec[i].first){
            checker=0;
            break;
        }
        else{
            s+=vec[i].second;
        }
    }
    if(checker>0)cout<<"YES"<<endl;
    else if(checker==0)cout<<"NO"<<endl;
    return 0;
}
Fahim Hassan
  • 61
  • 1
  • 9

3 Answers3

2

The correct syntax of pushing a value in a vector is : vectorname.push_back(value).

So, you need to write vec.push_back(make_pair(in1,in2)); instead of

vec[i].push_back(make_pair(in1,in2)).

If you need to insert the pair at specific index then you will have to use insert function instead of push_back because push_back inserts the element at the end of the vector.

To insert at i'th index kindly use:

vec.insert(vec.begin() + i, make_pair(int1, int2)).

Ayush Jain
  • 181
  • 7
2

In order to avoid making unnecessary copies of std::pair, you may want to construct std::pair in place by using std::vector::emplace_back:

vec.emplace_back(in1, in2);
NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • I don't quite understand it. I will have to look into it more. – Fahim Hassan Jul 10 '20 at 07:58
  • 1
    @FahimHassan when using `vec.push_back(make_pair(in1, in2));`, an object is being created with `make_pair(in1, in2)`. Then this object is copied to the `std::vector`. With `emplace_back`, this copy is avoided and, thus, you end up with better performance. Check more [here](https://stackoverflow.com/questions/4303513/push-back-vs-emplace-back). – NutCracker Jul 10 '20 at 08:02
  • 1
    This is amazing. Thanks! – Fahim Hassan Jul 10 '20 at 08:12
1

Change:

vec[i].push_back(make_pair(in1, in2));

to

vec.push_back(make_pair(in1, in2));

Also, if you change the order of these two lines:

    vector <pair<int,int>> vec;
    int s,n; cin>>s>>n;

and reserve size of the vector, you will not have to reallocate memory every time you do a push_back. This will make your program more efficient:

    int s,n; cin>>s>>n;
    //preallocate for 'n' elements
    vector <pair<int,int>> vec;
    vec.reserve(n);
Waqar
  • 8,558
  • 4
  • 35
  • 43
  • Yes, I have understood the problem here. My code works now. Thanks! – Fahim Hassan Jul 10 '20 at 07:55
  • 1
    It's worth to mention that you cannot combine second advice with first one. You need to either use `reserve()` if you want to continue using `push_back` or use `operator[]` if vector was created with `n` elements. – Yksisarvinen Jul 10 '20 at 08:06
  • @Yksisarvinen indeed. I updated to use `reserve()` instead as it is simpler and more straightforward – Waqar Jul 10 '20 at 09:02