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
DDDOriginal
2024-11-28 07:38:10753browse

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);
}

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

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));

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 } };

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!

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