I am using a std::vector of std::pair<int, int>.
std::vector< std::pair<int, int> > vec(n);
Where, n is the size of the std::vector.
I am taking input from stdin in this manner:
for(int i=0; i<n; ++i) std::cin>>vec[i].first>>vec[i].second;
Doing this, I get a segmentation fault. However, if I change my code to this:
for(int i=0; i<n; ++i){
int x, y;
cin>>x>>y;
vec[i] = std::make_pair(x, y);
}
It works just fine. I am unable to figure out what's wrong with the first one, since it is working in my PC on small inputs, but giving a SIGSEGV on large random input. Also, I get the same behavior on replacing the vector with a static array of pair.
Also, I have faced errors while using a for loop on a vector of pair. If I do this:
for(int i=0; i<n; ++i){
std::cout<<vec[i].first<<" "<<vec[i].second<<"\n"
}
However, if I change it to:
for(auto x: vec){
std::cout<<x.first<<" "<<x.second<<"\n"
}
It works just fine. What and where is the problem here?
Aucun commentaire:
Enregistrer un commentaire