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

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

Patricia Arquette
Release: 2024-12-05 06:14:13
Original
1045 people have browsed it

What's the Most Efficient Way to Initialize a 2D Vector in C  ?

Efficient Initialization of Two-Dimensional Vector using Constructors and Uniform Initialization

Consider the following code snippet:

std::vector< std::vector<int> > fog;
Copy after login

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

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

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

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

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!

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