Nick____9
Nick____9

Reputation: 71

C++ dynamically convert vector to be 2D

Given I've already declared a regular vector as a member variable:

std::vector<char> vec;

Can I convert this to a 2D vector in the constructor of my class if necessary?

if(true){
    //vec becomes a 2D vector with 2 rows
}

At this stage the vector will have nothing in it. It'll be an empty vector of an unknown column size. Is this possible?

I don't necessarily want to have to declare it as a 2D vector to start with because if the bool is false then it means I just need the 1 row.

I thought I would be able to push_back a new vector but that doesn't seem to be working

Upvotes: 0

Views: 121

Answers (2)

rng70
rng70

Reputation: 25

Unfortunately, you can't. Simply 1-D is 1-D and 2-D is 2-D. So, if you need a 2-D vector when the boolean operator is true then you can declare another 2-D vector, convert the previous one to 2-D using necessary push/pop and delete the previous one.

Code will look like this

    // declare 1-D vector 
    std::vector<char> vec;

    if(true){
             // declare 2-D one
             vector<vector<char> >t_vec;
             // do necessary conversion
             // delete previous one
             vec.clear();
    }

Upvotes: 0

Caleth
Caleth

Reputation: 63297

No.

A std::vector<char> is a different thing to a std::vector<std::vector<char>>.

What you can do is take a 2d view of your std::vector<char>. Elements from begin() to begin() + (size() / 2) are your first row, and those from begin() + (size() / 2) to end() are your second row.

Upvotes: 1

Related Questions