简体   繁体   English

2d push_back 不保存到向量值

[英]2d push_back doesnt save to vector values

I have a 2d vector which should save x and y coordinates.我有一个 2d 矢量应该保存 x 和 y 坐标。 Everything works as intended except saving this values to vector.除了将此值保存到向量之外,一切都按预期工作。 What did I do wrong?我做错了什么?

void Game::GetShips(Board &b)
{
    vector<vector<int>> shipCors;

    for (int i = 0; i < BOARDSIZE; i++) {

        for (int j = 0; j < BOARDSIZE; j++) {
            if (b.getSpaceValue(i, j) == SHIP) {
                cout << "X :"<< i<<"\n Y:"<<j<<'\n';
                shipCors[i].push_back(j);
              
            }
        }

    }
    cout<< shipCors.size()<<'\n';
 }

You declared an empty vector你声明了一个空向量

vector<vector<int>> shipCors;

So you may not use the subscript operator所以你可能不会使用下标运算符

shipCors[i].push_back(j);

You could write你可以写

for (int i = 0; i < BOARDSIZE; i++) {

    shipCors.resize( shipCors.size() + 1 );
    for (int j = 0; j < BOARDSIZE; j++) {
        if (b.getSpaceValue(i, j) == SHIP) {
            cout << "X :"<< i<<"\n Y:"<<j<<'\n';
            shipCors[i].push_back(j);
          
        }
    }

}

Pay attention to that as you are using the index i then you need to add a "row" of the vector even if the row will be empty after executing the inner for loop.请注意,当您使用索引i时,即使在执行内部 for 循环后该行将为空,您也需要添加向量的“行”。

It will be even better to resize the vector initially before the for loops like在 for 循环之前调整向量的大小会更好

vector<vector<int>> shipCors;
shipCors.resize( BOARDSIZE );

for (int i = 0; i < BOARDSIZE; i++) {

    for (int j = 0; j < BOARDSIZE; j++) {
        if (b.getSpaceValue(i, j) == SHIP) {
            cout << "X :"<< i<<"\n Y:"<<j<<'\n';
            shipCors[i].push_back(j);
          
        }
    }

}

An alternative approach is to have a vector declared like另一种方法是声明一个向量

std::vector<std::pair<int, int>> shipCors;

In this case your loop will look like在这种情况下,您的循环将如下所示

for (int i = 0; i < BOARDSIZE; i++) {

    for (int j = 0; j < BOARDSIZE; j++) {
        if (b.getSpaceValue(i, j) == SHIP) {
            cout << "X :"<< i<<"\n Y:"<<j<<'\n';
            shipCors.emplace_back(i, j);
          
        }
    }

}

Or to keep the data sorted you can declare a set like或者为了保持数据排序,您可以声明一个集合,例如

std::set<std::pair<int, int>> shipCors;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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