Home >Backend Development >C++ >What\'s the Most Efficient Way to Initialize a 2D std::vector in C ?

What\'s the Most Efficient Way to Initialize a 2D std::vector in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 04:36:12978browse

What's the Most Efficient Way to Initialize a 2D std::vector in C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn