Using std::vector<T> Containers - C++ STL

C++ examples for STL:vector

Introduction

Here's an example of creating a vector<> container to store values of type double:

std::vector<double> values;

You can add an element using the push_back() function for the container object. For example:

values.push_back(3.1415926);           // Add an element to the end of the vector

You can create a vector<> with a predefined number of elements, like this:

std::vector<double> values(20);        // Capacity is 20 double values

This container starts out with 20 elements that are initialized with zero by default.

You can specify a value that will apply for all elements:

std::vector<long> numbers(20, 99L);    // Capacity is 20 long values - all 99

You can use an index to set a value for an existing element or to use its current value in an expression. For example:

values[0] = 3.1415926;                      // Pi
values[1] = 5.0;                            // Radius of a circle
values[2] = 2.0*values[0]*values[1];        // Circumference of a circle

You can create a vector<> is to use an initializer list to specify initial values:

std::vector<unsigned int> primes { 2u, 3u, 5u, 7u, 11u, 13u, 17u, 19u};

The primes vector container will be created with eight elements with the initial values in the initializer list.


Related Tutorials