Why: push_back?

I was just wondering, why it's better to use push_back, when adding elements to an array, rather than just doing something like:

vec.x = 5

for example.
push_back grows the array to accomodate the new element. A vector has a capacity and a size. The capcity is how much physical storage is has available before needing to reallocate space on a push_back request. The size is how many elements are currently stored.

You can still write code like vec[3] = 5;, but that implies at 3 is a valid index into vec. A tested alternative vec.at(3) = 5; throws an exception if 3 is out of range.
Last edited on
thanks very much
Ok - so another quick question: I have the following:


1
2
3
4
5
6
7
8
vector<point2d> arraypoints;

for (int i = 0; i < 10; i++){

arraypoints[i].mX = (10 * rand() / float(RAND_MAX);

}


which is a snippet of the code i'm using, which doesn't use the push_back, or at (or any vector features).

So, with the above in mind, what's the syntax to change the above code, into something which utilises the correct notation?

If you want a vector of fixed size 10, your code might look like this.
1
2
3
4
5
const int maxpoints = 10;
std::vector<point2d> arraypoints(maxpoints);

for (int i = 0; i < maxpoints; ++i)
    arraypoints[i].mX = 10 * rand() / float(RAND_MAX);
Sure, i've been using that method already. But rather than using the line
 
arraypoints[i].mX = 10 * rand() / float(RAND_MAX);


would it be better to use the push_back, or is it absolutely fine the way you've written it above?
You can either initialize the vector with how many elements you want and then process it. Or you may add each time a new object to your vector and process it. I recommend the first method btw.

1
2
3
4
5
6
7
std::vector<point2d> arraypoints;

for (int i = 0; i < maxpoints; ++i){
    point2d myobject;
    myobject.mx = 10 * rand() / float(RAND_MAX);
    arraypoints.push_back(myobject);
}
Last edited on
If you're dealing with a fixed length array, the index operator is the thing to use.

If you want to grow the array, then you'd be required to use push_back.

You example uses an array of size zero but indexes into it, so it's technically incorrect. But I take it that's just a typo.
Topic archived. No new replies allowed.