I know the size of a vector, which is the best way to initialize it?
Option 1:
vector vec(3); //in .h
vec.at(0)=var1;
In the long run, it depends on the usage and numbers of the elements.
Run the program below to understand how the compiler reserves space:
vector
vec; for(int i=0; i<50; i++) { cout << "size=" << vec.size() << "capacity=" << vec.capacity() << endl; vec.push_back(i); }
size is the number of actual elements and capacity is the actual size of the array to imlement vector. In my computer, till 10, both are the same. But, when size is 43 the capacity is 63. depending on the number of elements, either may be better. For example, increasing the capacity may be expensive.