对矢量的更改<bitset> 会更改另一个矢量中的值

Changes to vector<bitset> change values in another vector

提供以下代码:

#include <iostream>
#include <bitset>
#include <set>
#include <string>
#include <vector>

using namespace std;

typedef pair<int, int> coordinate;
typedef vector<coordinate> path;

class Game {
private:
    vector<bitset<15>> board{15};
    vector<path> paths;
public:
    Game() {
        for (int i = 0; i < 15; i++) {
            string line;
            getline(cin, line);
            for (int j = 0; j < 15; j++) {
                if (line[j] == '.') {
                    board[i].set(j); // the problem no longer occurs after removing this line
                    if (paths.size() > 2)
                        cout << "A: " << paths[2].back().first << endl;
                    paths.emplace_back(1, make_pair(j, i));
                    if (paths.size() > 2)
                        cout << "B: " << paths[2].back().first << endl;
                }
            }
        }
    }
};

int main() {
    Game game;
    return 0;
}

我 运行 遇到问题,我的向量 paths 中的值被 board[i].set(j) 行更改; 。在我看来,这两个向量似乎完全不相关。 给定以下输入(这个问题发生在多个输入上,这只是我测试过的一个):

.........xx....
..xx.....xx....
..xx...........
...............
...............
.........xx....
....xx...xx....
....xx.........
...............
...xx..xx......
...xx..xx......
...............
...............
............xx.
............xx.

此输入产生以下输出:

A: 2
B: 2    
A: 2
B: 2
...
A: 2
B: 2
A: 3
B: 3
A: 3
B: 3
A: 7
B: 7
A: 15
B: 15
A: 31
B: 31
A: 63
B: 63
A: 127
B: 127
A: 255
B: 255
A: 511
B: 511
A: 1023
B: 1023
A: 2047
B: 2047
A: 4095
B: 4095
A: 8191
B: 8191
A: 16383
B: 16383
A: 32767
B: 32767
...
A: 32767
B: 32767
A: 32767
B: 32767

我尝试过的一件事是将 board[i].set(j); 更改为 board[i] |= 1 << j; 但这没有效果。

我无法弄清楚这些值以何种方式更改或如何修复,在此先感谢您的时间和帮助。

问题是初始化:

vector<bitset<15>> board{15};

这不是包含 15 个元素的向量,而是包含一个初始化值为 15 的元素的向量。因此 board[i] 超出了任何 i >= 1 的范围。这会导致未定义的行为,所以任何事情可能发生。

如果向量的大小无论如何都是固定的,std::array 可能是更好的选择:

std::array<std::bitset<15>, 15> board;

或者在构造函数初始化列表中初始化:

Game() : board(15) // intialize with 15 default-constructed elements
{ /* other logic */}