mlt wrote:
> What is the difference between using push_back or [] on a std::vector?
push_back appends a value at the end of the vector.
[] replaces the element at the given index.
> std::vector<int> temp(3);
The above creates a vector containing 3 default constructed elements.
The value of a default constructed int is 0, so the vector
contains {0, 0, 0}.
> for (int i=0; i<3; i++)
> {
> temp.push_back(i); // or
> // temp[i] = i;
> }
Using push_back in the above loop appends 0, 1, 2, so the vector
contains {0, 0, 0, 0, 1, 3} after the loop.
Using [] replaces the first three elements, so the vector
contains {0, 1, 2} after the loop.
|