std::vector

Std::vector is a collection type that stores data contiguously in memory, basically a dynamically sized array. It also has many methods for the access and manipulation of the data.

To use std::vector we will need to include the vector header:

#include <vector>
#include <string>

std::vector<std::string> motto {"Today", "is", "a", "good", "day", "to", "die"};
std::vector<int> surprise (20, 5); // Gives a vector of 20 fives.

Std::vector supports random access operators so is very fast to retrieve elements. Inserting an element at the back is also very fast but inserting elsewhere is very expensive. It supports all iterators. It is a good general purpose container to use as a first choice. If we get performance problems, try to identify and switch to a more suitable container.

Some common methods of the vector type are push_back, which adds a value to end of the vector, pop_back, which removes a value from the end of a vector, at, which gets or sets the value at the specified index, size, which returns how many items are in the vector, front, which returns the first value, and back which returns the last value. There is also the [] operator for setting and getting values. The difference with at is that at does range checking and throws an exception if we are outside the bounds. We can get access to the underlying array by using the data method.

We can loop a vector using both a standard and enhanced for loop.

#include <iostream>
#include <string>
#include <vector>

int main() {

    std::vector<std::string> motto {"Today", "is", "a", "good", "day"};
    motto.push_back("to");
    motto.push_back("die");

    std::cout << motto.front() << std::endl;
    std::cout << motto.back() << std::endl;
    std::cout << motto.at(3) << std::endl;

    for (const std::string &word : motto) {
        std::cout << word << " ";
    }

    std::cout << std::endl;

    return 0;
}

Read more about std::vector.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.