C++ Vectors .size()

#include
#include

int main() {

std::vectorstd::string grocery = {“Hot Pepper Jam”, “Dragon Fruit”, “Brussel Sprouts”};

// Add more

grocery.push_back(“Hot Pepper Jam”);
grocery.push_back(“Dragon Fruit”);
grocery.push_back(“Brussel Sprouts”);
grocery.push_back(“Artichoke”);

std::cout << grocery.size() << “\n”;

}

Why I have 7 in the terminal when I pressed “Run”?

2 Likes

In this line:

std::vectorstd::string grocery = {“Hot Pepper Jam”, “Dragon Fruit”, “Brussel Sprouts”};

you initialized new vector grocery with 3 values. Later you added four next elements with push_back method.

3 + 4 = 7 :slight_smile:

1 Like

So when I write .push_back - I add new values, and it isn’t the same?

Here is the documentation for std::vector::push_back -> http://www.cplusplus.com/reference/vector/vector/push_back/.

Adds a new element at the end of the vector, after its current last element.

So, when you use push_back the argument is added as a new element at the end of the vector and the size of the vector is incremented by one.

2 Likes

Thank you very much:tulip:

You’re very welcome :panda_face:

2 Likes

Great question and great answer! :slight_smile:

I’m adding more to the hint in the exercise @factoradic