Initializing Two-Dimensional std::vectors Efficiently
Consider the following code snippet:
std::vector< std::vector<int> > fog; 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); }
This method of initializing a two-dimensional std::vector appears inefficient. An alternative approach leveraging the std::vector::vector(count, value) constructor is available:
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, specify it as shown below:
std::vector<std::vector<int>> fog( ROW_COUNT, std::vector<int>(COLUMN_COUNT, 4));
Additionally, uniform initialization introduced in C 11 allows for concise initialization using {}:
std::vector<std::vector<int>> fog { { 1, 1, 1 }, { 2, 2, 2 } };
The above is the detailed content of What\'s the Most Efficient Way to Initialize a 2D std::vector in C ?. For more information, please follow other related articles on the PHP Chinese website!