I have a problem with pushing a class Point into a vector.
I have a class Point:
Point::Point(){
this->X=1000;
this->Y=1000;
}
Point::Point(int x1, int y1){
this->X = x1;
this->Y = y1;
}
I create a vector like this:
vector<Point> vecteurPTries(nombrePoint);
for(i = 0; i < nombrePoint; i++){
vecteurPTries.push_back(pointsTries[i]);
cout<<"vecteur "<<vecteurPTries.at(i).getX()<<" "<<vecteurPTries.at(i).getY()<<endl;
}
Instead of having:
point trie 487 3
point trie 492 42
point trie 430 272
point trie 440 165
point trie 423 209
point trie 327 229
point trie 307 249
point trie 340 112
point trie 44 378
point trie 73 158
I have:
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
vecteur 1000 1000
Can someone explain me why? What's the problem?
Thanks.
You don't show all the code, but I think the issue is that you use push_back to add entries to the end of the vector, but you instantiated the vector with size nombrePoint
, which will cause it to create nombrePoint
values that are default initialized. You then push another nombrePoint
values on the end but you're not seeing those because your loop index is from 0
to nombrePoint
.
What you want to do instead is
vector<Point> vecteurPTries;
vecteurPTries.reserve(nombrePoint);
This will create an empty vector for which you have reserved space for nombrePoint
elements (not strictly necessary but will reduce re-allocation and relocation during the loop). The loop as given will then populate the first nombrePoint
elements of this vector as you were intending.