This question already has an answer here:
- std::vector::resize() vs. std::vector::reserve() 6 answers
- Why doesn't this vector assignment work? 1 answer
- Why aren't these vectors equal? 1 answer
Snippet1: The following snippet prints out 0 1 but returns an empty vector.
vector<int> trial() {
vector<int> ret;
ret.reserve(2);
ret[0] = 0;
ret[1] = 1;
cout << ret[0] << " " << ret[1] << "\n";
return ret;
}
Snippet 2: The following snippet prints out 0 1 and returns a vector contains {0,1}.
vector<int> trial() {
vector<int> ret;
ret.push_back(0);
ret.push_back(1);
cout << ret[0] << " " << ret[1] << "\n";
return ret;
}
Why doesn't snippet 1 work like snippet 2. If I am reserving memory and adding values to the vector.
Aucun commentaire:
Enregistrer un commentaire