Initializing a two-dimensional std::vector can be a cumbersome task. A common approach is to manually create and append rows to the vector, as exemplified by the provided code. However, this method can be inefficient and prone to errors.
An alternative solution is to leverage the std::vector::vector(count, value) constructor. This constructor accepts two parameters: the desired number of rows and a default value for each row's elements. By specifying the appropriate values for these parameters, we can initialize the vector in a single statement:
std::vector<std::vector<int>> fog(ROW_COUNT, std::vector<int>(COLUMN_COUNT)); // Defaults to zero initial value
If a default value other than zero is desired, it can be specified as the second argument to the constructor:
std::vector<std::vector<int>> fog(ROW_COUNT, std::vector<int>(COLUMN_COUNT, 4));
Uniform Initialization
C 11 introduced uniform initialization, providing another concise syntax for initializing a 2D vector:
std::vector<std::vector<int>> fog { { 1, 1, 1 }, { 2, 2, 2 } };
This approach utilizes curly braces to initialize rows within the vector. Each inner curly brace-enclosed list represents a row, with each element initialized to the specified value.
By employing these techniques, we can initialize a 2D std::vector efficiently and elegantly, avoiding the complexities of manual initialization.
The above is the detailed content of How Can I Efficiently Initialize a 2D std::vector in C ?. For more information, please follow other related articles on the PHP Chinese website!