I have a class that has a member unordered_set<int>as follows:
I have the following class definition, followed by its regular and copy constructors, as well as some other function that modifies the set (deleted irrelevant code segments, since the class is very long):
#include <iostream>
#include <unordered_set>
#include <random>
class HexBoard {
public:
HexBoard(int n);
HexBoard(const HexBoard &obj);
std::unordered_set<int> emptyPositions();
private:
std::unordered_set<int> empty_positions;
};
HexBoard::HexBoard(int n) {
for (int i = 0; i < n * n; i++) {
empty_positions.insert(i);
}
}
HexBoard::HexBoard(const HexBoard &obj) : empty_positions(obj.empty_positions) {};
void HexBoard::placeStone(int i) {
checkBounds(i);
empty_positions.erase(i);
}
std::unordered_set<int> HexBoard::emptyPositions() {
return empty_positions;
}
I have another class that contains an instance of this HexBoard. It has a function that will copy this board to another variable using the copy constructor:
class Game {
public:
Game(HexBoard::HexBoard *board) : board(board) {};
private:
HexBoard *board;
void monteCarlo(int position);
};
void Game::monteCarlo(int position) {
HexBoard *another_board = new HexBoard(*board);
int count = 0;
while (count < 5) {
count++;
std::uniform_int_distribution<unsigned> dis(
0, another_board->emptyPositions().size() - 1
);
std::cout << "Empty positons:\n";
for (const auto& pos : another_board->emptyPositions()) {
std::cout << pos << " ";
}
std::cout << "\n";
int n = dis(gen);
std::cout << "Picked random n: " << n << "\n";
auto it = another_board->emptyPositions().begin();
std::cout << "it begin: " << *it << "\n";
std::advance(it, n);
std::cout << "it advance: " << *it << "\n";
int absolute_position = *it;
std::cout << "picked " << absolute_position << "\n";
}
}
In a function monteCarlo, suppose the contents of the set emptyPositionswere originally 8, 7, 6, 5, 4, 3, 2, 1, the output of this function is usually:
Empty positons:
8 7 6 5 4 3 2 1
Picked random n: 4
it begin: 2
Segmentation fault: 11
segfault? , empty_positions.erase(i);, , .
Picked random n stdout segfaults ( ):
std::cout << "set buckets contain:\n";
for ( unsigned i = 0; i < ai_board->emptyPositions().bucket_count(); ++i) {
std::cout << "bucket #" << i << " contains:";
for ( auto j = ai_board->emptyPositions().begin(i);
j != ai_board->emptyPositions().end(i); ++j)
std::cout << " " << *j;
std::cout << std::endl;
}
:
set buckets contain:
Segmentation fault: 11
std::advance(it, n); .
.