简体   繁体   中英

Initializing a Three Dimensional Vector in a C++ Class

Using the following code I would like to move a multidimensional vector in various directions. Unfortunately right after initializing I get an EXC_BAD_ACCESS error.

Direction: Values from 0 to 2 for x,y and z movement

Steps: Only -1 and 1 (Back, Forward)

Container: Multidimensional Vector

if (verMove(direction, steps)==true) {

std::vector<int> val(4,0);
std::vector<std::vector<int>> val2(4,val); /// ERROR
std::vector<std::vector<std::vector<int>>> newContainer(4,val2);

// Move in X Direction
for (int a=0; a<4; a++) {
    for (int b=0; b<4; b++) {
        for (int c=0; c<4; c++) {

            int d;

            if (steps<0)
                d=3;
            else
                d=0;

            switch (direction) {
                case 0:
                    if (c==d)
                        newContainer[a][b][c] = 0;
                    else if (steps>0)
                        newContainer[a][b][c] = this->container[a][b][c-1];
                    else
                        newContainer[a][b][c] = this->container[a][b][c+1];
                    break;
                case 1:
                    if (b==d)
                        newContainer[a][b][c] = 0;
                    else if (steps>0)
                        newContainer[a][b][c] = this->container[a][b-1][c];
                    else
                        newContainer[a][b][c] = this->container[a][b+1][c];
                    break;
                case 2:
                    if (a==d)
                        newContainer[a][b][c] = 0;
                    else if (steps>0)
                        newContainer[a][b][c] = this->container[a-1][b][c];
                    else
                        newContainer[a][b][c] = this->container[a+1][b][c];
                    break;
            }
        }
    }
}

    replaceContainer(newContainer);

} else {

    return;

}
}

Your code (with vectors) works. Live example . Try to add space betwen two > signs ( >> ) and check if it helps.

Another way to initialize vector is using std::initializer_list like this:

    std::vector<std::vector<std::vector<int>>> myVec = 
    { 
        { 
            { 0, 1 }, 
            { 2, 3} 
        }, 
        { 
            { 4, 5 }, 
            { 6, 7 } 
        } 
    };

Live example #2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM