std::vector (C++)

std::vector is a resizable array from the C++ standard library. It stores elements of one type in contiguous memory and can grow or shrink at runtime.

C++

Vectors handle their own memory automatically, so you can add elements with .push_back() without worrying about allocation. Access elements by index with [] and check the count with .size().

Defined in <vector>, it is the go-to container in modern C++ and is far safer than a raw array.

Syntax

std::vector<type> name = { values };

Examples

C++

#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {1, 2, 3};
    nums.push_back(4);
    std::cout << nums.size() << " " << nums[3] << std::endl;
    return 0;
}

Output:

4 4

Learn it in a lesson

See also

Back to the Dictionary