Efficient Initialization of Two-Dimensional Vector using Constructors and Uniform Initialization
Consider the following code snippet:
std::vector< std::vector<int> > fog;
To initialize this two-dimensional vector, numerous developers utilize a manual approach involving nested loops:
for(int i=0; i<A_NUMBER; i++) { std::vector<int> fogRow; for(int j=0; j<OTHER_NUMBER; j++) { fogRow.push_back(0); } fog.push_back(fogRow); }
However, this manual initialization technique may not be optimal. An alternative approach involves utilizing the std::vector::vector(count, value) constructor, which accepts an initial size and a default value:
std::vector<std::vector<int>> fog( ROW_COUNT, // Specifies the number of rows std::vector<int>(COLUMN_COUNT) // Initializes each row with a default value of 0 );
If a default value other than zero is desired, such as 4, the following syntax can be utilized:
std::vector<std::vector<int>> fog( ROW_COUNT, std::vector<int>(COLUMN_COUNT, 4) // Initializes each row with a default value of 4 );
Moreover, C 11 introduced uniform initialization, providing a concise method for initializing containers. Uniform initialization employs curly braces ({}) to set the initial values:
std::vector<std::vector<int>> fog { { 1, 1, 1 }, { 2, 2, 2 } };
By employing these constructors and uniform initialization techniques, developers can efficiently initialize two-dimensional vectors, enhancing code readability and performance.
The above is the detailed content of What\'s the Most Efficient Way to Initialize a 2D Vector in C ?. For more information, please follow other related articles on the PHP Chinese website!