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
Release: 2024-12-04 04:36:12
Original
943 people have browsed it

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);
}
Copy after login

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
Copy after login

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));
Copy after login

Additionally, uniform initialization introduced in C 11 allows for concise initialization using {}:

std::vector<std::vector<int>> fog { { 1, 1, 1 },
                                    { 2, 2, 2 } };
                           
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template