Home > Backend Development > C++ > How Can I Optimize the Initialization of a 2D std::vector in C ?

How Can I Optimize the Initialization of a 2D std::vector in C ?

DDD
Release: 2024-11-28 07:38:10
Original
737 people have browsed it

How Can I Optimize the Initialization of a 2D std::vector in C  ?

Optimal Initialization of a Two-Dimensional std::vector

Initializing multidimensional std::vectors presents certain challenges, particularly when aiming for efficient code. Consider the given example:

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 approach requires multiple nested loops and appears somewhat tedious. A more optimal solution exists using the std::vector::vector(count, value) constructor:

std::vector<std::vector<int>> fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT)); // Defaults to zero initial value
Copy after login

In this case, the constructor takes an initial size and a default value. If a different default value is desired, it can be specified as follows:

std::vector<std::vector<int>> fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT, 4));
Copy after login

Furthermore, utilizing uniform initialization introduced in C 11 provides a concise and readable method for vector initialization:

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

The above is the detailed content of How Can I Optimize the Initialization of 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template