Home > Software engineering >  Taking Input in 3D vector
Taking Input in 3D vector

Time:04-18

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 :)

CodePudding user response:

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?

CodePudding user response:

You should replace int a; with char a; since the input provided are characters.

Also, you can make your code more efficient and readable by using range based for loop as shown below:

int n = 0, m = 0;
cin>>n>>m;
vector<vector<vector<char>>> v3(n, std::vector<std::vector<char>>(m, std::vector<char>(4)));
for(auto& row: v3){
        
    for(auto& col: row){

        for(char& element: col){
                cin>>element;     
        }   
    }   
}

Working demo

  • Related