Skip to content

Vectors

Vectors

std::vector is a safe container for arrays of dynamic size.

It automatically coordinates the process of allocating and deallocating memory for the elements as required.

1
#include <vector>

1
std::vector<int> v = {1, 2, 3};

1
2
3
for (size_t i = 0; i < v.size(); ++i) {
    std::cout << "v[" << i << "]: " << v[i] << '\n';
}

1
2
3
4
std::cout << "v.size(): " << v.size() << '\n';
std::cout << "v.empty(): " << v.empty() << '\n';
std::cout << "v.front(): " << v.front() << '\n';
std::cout << "v.back(): " << v.back() << '\n';

1
2
3
4
std::cout << "&v: " << &v << '\n';
std::cout << "&v[0]: " << &v[0] << '\n';
std::cout << "&v[1]: " << &v[1] << '\n';
std::cout << "&v[2]: " << &v[2] << '\n';

1
2
3
for (size_t i = 0; i < v.size(); ++i) {
    std::cout << "v[" << i << "]: " << v[i] << '\n';
}

1
v.push_back(5);

1
2
// We might still need the underlying raw array to interact with old code
std::cout << "Underlying raw vector: " << v.data() << '\n';

1
2
3
// vector<T,N> has no fixed size in bytes
// sizeof(v) has only the size of the pointers to manage v
std::cout << "sizeof(v): " << sizeof(v) << '\n';

1
2
3
4
5
6
std::vector<std::vector<double>> matrix(10, std::vector<double>(3, 0));
for (size_t i = 0; i < matrix.size(); ++i) {
    for (size_t j = 0; j < matrix[i].size(); ++j) {
        matrix[i][j] = 0.5 * i + 0.8 * j;
    }
}

1
2
3
4
5
6
7
for (const auto &row : matrix) {
    double sum = 0.;
    for (const auto &col : row) {
        sum += col;
    }
    std::cout << "Row average " << sum / row.size() << '\n';
}

Share Snippets