More vector functions

More vector functions#

Size#

We can always get the number of elements in a vector via the .size() function:

std::vector<int> int_vec{1, 2, 3, 4, 5};

int nlen = int_vec.size();

Note

size() technically returns a value of type std::size_t, and here we implicitly cast it to an int. We learn more about casting later.

Adding to a vector#

Lets see how to create a vector and add some data to it. We use the member function .push_back() to this. This will add an element to the end of the vector.

Here’s a simple example:

Listing 31 simple_vector.cpp#
#include <iostream>
#include <vector>

int main() {
    std::vector<double> container;

    container.push_back(10.0);
    container.push_back(-1.0);
    container.push_back(15.3);
    container.push_back(3.14159);

    std::cout << container[3] << std::endl;
    std::cout << "the vector has " << container.size()
              << " elements" << std::endl;

}

We use push_back several times to add data to the end of a vector. Here we are using the . operator to indicate that we are performing the push_back on the vector container that we created.

Note

push_back is a member function of the vector class. There are others that we will see shortly.

try it…

We can see the size of the vector increase each time we add an element using .push_back().