0

I just saw in a tutorial someone who used in the same file both:

myVector.back().push_back();
myVector.push_back();

What's the difference?

Cory Kramer
119k19 gold badges176 silver badges233 bronze badges
asked Nov 7, 2014 at 19:40
0

2 Answers 2

5

The first had to be something like

vector<vector<T>>

Otherwise it would not work. back() returns the element at the back of the vector. When you say

myVector.back().push_back();

it would be accessing the last vector<T>, then calling push_back() on that inner vector

If it is the case that myVector is a vector<vector<T>>, then

myVector.push_back();

would be pushing back an empty vector<T> whereas

myVector.back().push_back();

would be pushing back a default T onto the last vector<T> in myVector.

answered Nov 7, 2014 at 19:41
Sign up to request clarification or add additional context in comments.

3 Comments

In my case myVector is a vector containing a class
In that case, back() would return an instance of your class that was the last element in the vector. So unless your class has a push_back() method, then the first version will not compile.
So if I got it right, back() points the last item in the vector and then the push_back() adds something to the end of this item.
1
myVector may be a std::vector<std::vector<T>>
answered Nov 7, 2014 at 19:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.