std::vector and push_back()

M

mlt

What is the difference between using push_back or [] on a std::vector?

std::vector<int> temp(3);
for (int i=0; i<3; i++)
{
temp.push_back(i); // or
// temp = i;
}


When I read from the vector later I get an error if I use push_back() above
but no error when I use [].
 
A

Annie Testes

mlt said:
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;
}


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.
 
Z

ZikO

mlt said:
What is the difference between using push_back or [] on a std::vector?

It's a big difference. These are two completely different things.

operator[] table-like you can only use within the range of
0 - (size()-1) and by means of which you can read into or write from the
vector. However, if you go out of its range you will likely crash the
program.

push_back() method, on the other hand, adds new value at the end of the
vector increasing its size and you can't use it to read from the vector.

There's also at() method which works similarly to [] but throws
exception if you go out of range.
std::vector<int> temp(3);
for (int i=0; i<3; i++)
{
temp.push_back(i); // or
// temp = i;
}


When I read from the vector later I get an error if I use push_back()
above but no error when I use [].


"i" is a local variable within the for-loop scope. Since you've left the
scope, i no longer exists. This is first thing which might cause error.
Second, if you somehow defined this variable at start and not
initialized it, it can contains anything like 0,2, 200, 465123 depending
of where and how you defined that. if it's let's say local variable it
might have 1425 then your code would look at that particular time like
below:

//...
temp.push_back(1425); // 1425 put at 4th index ( = 3, from 0); size()=4;
temp[1425] = 1425; // very wrong line! essentially you tries to refer
// to not existing index (1425), it's likely to
// crash !!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top