Initializing a two-dimensional std::vector
Asked Answered
K

13

194

So, I have the following:

std::vector< std::vector <int> > fog;

and I am initializing it very naively like:

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

And it feels very wrong... Is there another way of initializing a vector like this?

Kipton answered 15/7, 2013 at 20:21 Comment(2)
I would recommend a 1d vector implementation for a 2d vector if you don't require more space than std::vector<int>::max_size(). HereAscertain
It would have been nice if at least one of the answers didn't involve copying the inner vector: memset is faster than memcpy (and calloc even better if operator new gets inlined).Diametral
C
356

Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value:

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

If a value other than zero, say 4 for example, was required to be the default then:

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

I should also mention uniform initialization was introduced in C++11, which permits the initialization of vector, and other containers, using {}:

std::vector<std::vector<int> > fog { { 1, 1, 1 },
                                    { 2, 2, 2 } };
                           
Choreodrama answered 15/7, 2013 at 20:24 Comment(3)
What if I make the storage class of the std :: vector <std :: vector <int>> as static ?Hysterectomize
reference for Error: "Expected parameter declarator": https://mcmap.net/q/130155/-vector-declaration-quot-expected-parameter-declarator-quot-duplicateManhole
In this way, it seems that first a template vector is created and then it's copied ROW_COUNT times. So there will be ROW_COUNT + 1 vector<int> created, is it right?Agronomy
O
157

Let's say you want to initialize a two-dimensional vector, m*n, with the initial value to be 0. We could do this:

#include <iostream>

int main(){
    int m = 2, n = 5;

    vector<vector<int>> vec(m, vector<int> (n, 0));

    return 0;
}
Ommatophore answered 22/5, 2018 at 23:57 Comment(1)
Just earned a 'Good Answer' because of this answer. Other people already gave the same answer, but those who upvote this one may be similar to me when I came to this post, that we didn't recognize that some other answers are actually the same answer. I think it might be because three reasons: 1) this code could be copied, pasted, and run right away 2) std:: makes it longer and people might like short and direct answer; 3) the long naming of variable confuses beginners. I'm a beginner too, don't really know how important we need std::, need a code runnable so I know what each variable doesOmmatophore
R
37

There is no append method in std::vector, but if you want to make a vector containing A_NUMBER vectors of int, each of those containing other_number zeros, then you can do this:

std::vector<std::vector<int>> fog(A_NUMBER, std::vector<int>(OTHER_NUMBER));
Risarise answered 15/7, 2013 at 20:25 Comment(0)
F
11

The general syntax, as depicted already is:

std::vector<std::vector<int> > v (A_NUMBER, std::vector <int> (OTHER_NUMBER, DEFAULT_VALUE))  

Here, the vector 'v' can be visualised as a two dimensional array, with 'A_NUMBER' of rows, with 'OTHER_NUMBER' of columns with their initial value set to 'DEFAULT_VALUE'.

Also it can be written like this:

std::vector <int> line(OTHER_NUMBER, DEFAULT_VALUE)
std::vector<std::vector<int> > v(A_NUMBER, line)

Inputting values in a 2-D vector is similar to inputting values in a 2-D array:

for(int i = 0; i < A_NUMBER; i++) {
     for(int j = 0; j < OTHER_NUMBER; j++) {
         std::cin >> v[i][j]
     }
}

Examples have already been stated in other answers....!

Futurity answered 4/3, 2018 at 9:25 Comment(0)
N
8

I think the easiest way to make it done is:

std::vector<std::vector<int>>v(10, std::vector<int>(11, 100));

10 is the size of the outer or global vector, which is the main one, and 11 is the size of inner vector of type int, and initial values are initialized to 100!

Nephrosis answered 17/6, 2019 at 22:12 Comment(0)
S
8

The recommended approach is to use a fill constructor to initialize a two-dimensional vector with a given default value:

std::vector<std::vector<int>> fog(M, std::vector<int>(N, default_value));

where, M and N are dimensions for your two-dimensional vector.

Sniggle answered 2/8, 2019 at 12:15 Comment(0)
R
7

Here is what worked for me:

vector<vector<int>> minA{ROW_SIZE, vector<int>(COLUMN_SIZE, VALUE)};
Rutan answered 4/7, 2021 at 17:54 Comment(1)
interesting, I thought we should enclose ROW_SIZE, vector<int>(COLUMN_SIZE, VALUE) with parentheses, instead of curly braces (I know that yours works too).Adelaideadelaja
C
4

This answer will help to easily initialize 2d vector after declaration.

int n=4,m=3;
int default_value = 0;

std::vector<std::vector<int>> matrix;

matrix.resize(m, std::vector<int>(n, default_value));
Copley answered 10/9, 2021 at 20:22 Comment(0)
U
3

Suppose you want to initialize a two-dimensional integer vector with n rows and m column, each having value 'VAL'.

Write it as

std::vector<vector<int>> arr(n, vector<int>(m, VAL));

This VAL can be an integer type variable or constant, such as 100.

Unific answered 26/10, 2019 at 14:0 Comment(0)
P
1

This code snippet copies one two-dimensional vector to another. And gives us a clear picture of how to initialize the 2D vector.

void copyVectorToVector(vector<vector<int>> matrix) {

        int rowNumber = matrix.size();
        int columnNumber = matrix[0].size();
        vector<vector<int>> result(rowNumber, vector<int> (columnNumber, 0));

        for(int i=0;i<matrix.size();i++){
            for(int j=0;j<matrix[i].size();j++){
                result[i][j] = matrix[i][j];
                cout<<result[i][j]<<" ";
            }
            cout<<endl;
        }
}
Pave answered 22/3, 2021 at 11:27 Comment(0)
J
-1

multiplication table with 2D vector the first 10 is for ROW, second 10 for COLUMN

std::vector<std::vector<int>> multiplication (10,std::vector<int>(10));
for(int i{0}; i<multiplication.size(); ++i){
    for(int j{0}; j<multiplication[i].size(); ++j){
        multiplication[i][j] = j * i;
    }
}

for(int i{1}; i < multiplication.size(); ++i){
    for(int j{1}; j < multiplication[i].size(); ++j){
        std::cout<<multiplication[i][j]<<"\t";
    }
    printf("\n");
}
Jairia answered 11/9, 2021 at 16:6 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Gentile
T
-1

Additionally, if someone wants to initialize only the first col values to some different value(say 2) from the rest of the default values(say 1).

int rows = 3, cols = 4;
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 1));  
for (int r = 0 ; r < rows ; r++) matrix[r][0] = 2;
2 1 1 1
2 1 1 1
2 1 1 1
Tetreault answered 19/8, 2022 at 7:43 Comment(0)
T
-3

My C++ STL code to initialise a 5*3 two-dimensional vector with zero:

#include <iostream>
using namespace std;
#include <vector>

int main()
{
    // If we want to initialise a two-dimensional vector with 0;
    vector<vector<int>> v1(5, vector<int>(3, 0));

    for(int i=0; i<v1.size(); i++)
    {
        for(int j=0; j<v1[i].size(); j++)

            cout << v1[i][j] << " ";

            cout << endl;
        }
    }
Tipton answered 25/1, 2020 at 6:4 Comment(2)
The code as posted will not compile; it is incomplete.Petrapetracca
The code ought to be explained. At first glance, it looks like it doesn't do anything due to the dominating nested for loops and other ceremony, but the magic is presumably in vector<vector<int>> v1(5, vector<int>(3, 0));?Petrapetracca

© 2022 - 2024 — McMap. All rights reserved.