Home > Backend Development > C++ > How Can I Efficiently Initialize a 2D std::vector in C ?

How Can I Efficiently Initialize a 2D std::vector in C ?

Linda Hamilton
Release: 2024-12-02 22:52:14
Original
887 people have browsed it

How Can I Efficiently Initialize a 2D std::vector in C  ?

Efficiently Initializing a 2D std::vector

Initializing a two-dimensional std::vector can be a cumbersome task. A common approach is to manually create and append rows to the vector, as exemplified by the provided code. However, this method can be inefficient and prone to errors.

An alternative solution is to leverage the std::vector::vector(count, value) constructor. This constructor accepts two parameters: the desired number of rows and a default value for each row's elements. By specifying the appropriate values for these parameters, we can initialize the vector in a single statement:

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, it can be specified as the second argument to the constructor:

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

Uniform Initialization

C 11 introduced uniform initialization, providing another concise syntax for initializing a 2D vector:

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

This approach utilizes curly braces to initialize rows within the vector. Each inner curly brace-enclosed list represents a row, with each element initialized to the specified value.

By employing these techniques, we can initialize a 2D std::vector efficiently and elegantly, avoiding the complexities of manual initialization.

The above is the detailed content of How Can I Efficiently 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