Uniform initialization uses curly braces to initialize objects and values in C++. It provides a consistent alternative to older parentheses or assignment syntax, including int x{42}. section 1.4.1 section 2.1
Brace syntax is especially useful with containers:
- std::vector<int> data{1} creates a vector containing one integer, whereas std::vector<int> data(1) creates a vector with one element initialized to zero. section 2.1
- An initializer list can contain several values, such as {1, 2, 3}, and supplies the vector's contents. section 2.1
- Braces reject narrowing conversions: constructing vector<int> from {1, 2.3} produces a compiler error instead of silently converting the double. section 2.1
- The syntax also initializes empty or calculated values, as in int n{} and std::vector next_row{1}. section 2.2.2 section 3.3.3
Generating Pascal's triangle
Initialize the first row with std::vector<int> next_row{1}, then add calculated values with emplace_back. Braces express the known starting value while the vector grows procedurally. section 2.2.2
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();
}
Inspect a complete C++ example that initializes a vector with braces and displays its contents using a range-based for loop. section 2.1

