Jason Statham
Jason Statham

Reputation: 25

I want to create a 2D vector with each index being a vector of int

I want my data structure to look something like this when populated:

[[1, 2, 3] [3, 3, 3] [4, 4, 4]]
[[5, 4, 5] [3, 4, 5] [3, 3, 3]]

I'm not sure where to go from here. I've tried doing:

vector<vector<vector<int> > > x;

But I'm having trouble populating it. I think it's basically a matrix of vectors? I'm just not sure how to go about it.

EDIT: Sorry, I should've specified a bit more.

The core functionality of my program is to create multiple vector of size 3 and push them 1 by 1 in a 30x3 matrix of vectors. The matrix will be initially completely empty.

I want to be able to push a vector at a specific row, similar to something like this

vector<int> y{1, 2, 3};
x.at(row).push_back(y);

I'm not sure if that's the correct syntax of how to approach that but I want that to be the final functionality.

My goal is to create a 30x3 matrix with each index in the matrix being a vector of size 3

Upvotes: 0

Views: 129

Answers (2)

Galik
Galik

Reputation: 48625

It seems like you want this:

std::vector<std::vector<std::vector<int>>> x(30, std::vector<std::vector<int>>(3, std::vector<int>(3)));

The constructor I am using takes (std::size_t n, T t) as in n elements of type T.

If you want to replace a vector in a given cell, you can use:

x[2][4] = {2, 7, 9};

Or you can replace an entire row of 3like this:

x[1] = {{2, 7, 9}, {1, 1, 8}, {6, 2, 1}};

Upvotes: 1

Jarod42
Jarod42

Reputation: 217418

use {} instead of []:

std::vector<std::vector<std::vector<int>>> x{
    {{1, 2, 3}, {3, 3, 3}, {4, 4, 4}},
    {{5, 4, 5}, {3, 4, 5}, {3, 3, 3}}
};

Upvotes: 1

Related Questions