std::vector is a dynamically sized sequence container that stores elements for flexible access and manipulation. It is a practical starting point for learning modern C++ containers. section 1.0 section 2.0
Use a vector to:
- Initialize elements with uniform initialization, such as std::vector<int> data{1}; distinguish this from std::vector<int> data(1), which creates one value initialized to zero. section 2.1
- Traverse elements with range-based for loops, or use iterators and algorithms when needed. section 1.4.3 section 2.1
- Add elements with push_back, emplace_back, insert, or emplace; emplace constructs an element in place, while push_back accepts a completed value. section 2.2.2
- Store nested sequences, such as std::vector<std::vector<int>>, and vary the number of elements at run time. section 2.2.2 section 6.1.3
Pascal’s triangle
Represent each row as a vector<int>. Build the next row from adjacent values in the previous row, add 1 at both ends, and collect rows in a vector of vectors. Returning data separately from display keeps the calculation easier to test. section 2.0 section 2.2.2
Passing a temporary vector to push_back can use the rvalue overload and move its elements instead of copying them. emplace_back can construct the new element directly in the destination vector. section 2.2.3 section 2.2.3
Listing 2.1 Filling and displaying a container
#include <iostream> #1
#include <vector> #1
void generate_triangle()
{
std::vector<int> data{ 1 }; #2
for (auto number : data) #3
{
std::cout << number << ' ';
}
std::cout << '\n';
}
int main()
{
generate_triangle();
}
Compile and run a minimal vector program that initializes one element and displays it with a range-based for loop. section 2.1










