push_back versus operator[] assignment in c++ vectors -
can please explain me in detail why following code vectory assignment size of vecy zero? also, begin , end iterators stuck @ first node. seems reserve works push , need construct vector size if want iterators vectors , size work expected. assuming push_back doing type of allocation straight assignment not in case? looking details explaining can make sure understand happening reserve , push_back versus constructing size element , doing assignment in vecx example.
#include <iostream> #include <vector> int main ( int argc, char *argv[]) { std::vector<int> vecx(2); vecx[0] = 1; vecx[1] = 2; std::cout << " vecx0 item: " << vecx[0] << std::endl; std::cout << " vecx1 item: " << vecx[1] << std::endl; std::cout << " vectorx size: " << vecx.size() << std::endl; std::vector<int> vecy; vecy.reserve(2); vecy[0] = 1; vecy[1] = 2; std::cout << " vecy0 item: " << vecy[0] << std::endl; std::cout << " vecy1 item: " << vecy[1] << std::endl; std::cout << " vectory size: " << vecy.size() << std::endl; } output vecx0 item: 1 vecx1 item: 2 vectorx size: 2 vecy0 item: 1 vecy1 item: 2 vectory size: 0
std::vector<int> vecy; vecy.reserve(2); vecy[0] = 1; vecy[1] = 2; this code wrong , evokes undefined behavior1. when reserve vector, set capacity, not size.
you need either push_back, or construct vector did in example 1.
"undefined behavior" : invokes undefined behavior because of out-of-range call operator[] if call vector::operator[n] n > vec.size(), behavior undefined.
Comments
Post a Comment