Search code examples
c++data-structuresstdvector

How to take 3 dimensional input for 3D vector?


I have to take input in a 3D vector, of dimension (n,m,4). I have written the following piece of code, which is not working don't know why, please lemme know what I am doing wrong.

cin>>n>>m;
vector<vector<vector<char>>> v3;
for(int i=0;i<n;i++){
    vector<vector<char>> v2;
    for(int k=0;k<m;k++){
        vector<char> v1;
        char a;
        for(int j=0;j<4;j++){
            cin>>a;
            v1.push_back(a);
        }
        v2.push_back(v1);
    }
    v3.push_back(v2);
}

Sample Input:-

2 4
G Y B R
B G R Y
G Y B R
G R B Y
B Y G R
G B R Y
B R G Y
B R G Y

Thanks in advance :)


Solution

  • You haven't described the problem. Is it a compilation error? A runtime error?

    Anyway - you're code compiles on MSVC (replaced int with char as already suggested).

    But it is implemented in an inefficient way, because it involves a lot of copying around std::vectors and using push_back will cause reallocations of the vectors.

    Since you know the sizes in advances, it is better to allocate beforehand and just fill the std::vectors.

    Something like:

    int n=0, m=0;
    std::cin >> n >> m;
    std::vector<std::vector<std::vector<char>>> v3(n);
    for (auto & v2 : v3) {
        v2.resize(m);
        for (auto & v1 : v2) {
            v1.resize(4);
            for (auto & val : v1) {
                std::cin >> val;
            }
        }
    }
    

    BTW - It's not a good idea to use using namespace std. Always better to avoid it and use std::vector, etc. You can see why here: Why is "using namespace std;" considered bad practice?