问题
For a project, I have an opening table that I decided to put in a std::unordered_map
. Unfortunately, I am restricted to hard-coding the entire map. So, I decided to split the initialization into multiple files.
class OpeningBook
{
public:
OpeningBook();
private:
std::unordered_map<std::string, int> opening_database_;
void init1();
void init2();
void init3();
void init4();
void init5();
};
and the constructor just calls the init
functions:
OpeningBook::OpeningBook()
{
init1();
init2();
init3();
init4();
init5();
}
All of which just look like this:
void OpeningBook::init1()
{
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-1000001100000-1-1000",5000));
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-1000000100000-1-1100",5000));
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-1000000100001-1-1000",5000));
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-1000000100000-1-1010",5000));
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-1000000100010-1-1000",5000));
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-1000000100000-1-1001",5000));
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-100000010000-11-1000",0));
opening_database_.insert(std::pair<std::string, int>("0001000000-10000001000000-100000010000-10-1100",5000));
// continues
}
However, as soon as my code hits the opening brace in init1()
, it throws a stack overflow exception. I thought that a stack overflow couldn't occur because an unordered_map
is on the heap. What's going on? and what can I do to fix this?
回答1:
How many items are you inserting in each initx()
method? If it's many thousands, then it's possible that the compiler is generating code that uses a large number of temporaries on the stack, and simply asks for more stack space than there is available.
Try splitting your initialisation methods up further and see if that solves the problem.
A better approach might be to have a table which contains the initialisation data:
static const struct {
const char *str;
int n;
} DatabaseInitData[] = {
{"0001000000-10000001000000-1000001100000-1-1000",5000},
{"0001000000-10000001000000-1000000100000-1-1100",5000},
{"0001000000-10000001000000-1000000100001-1-1000",5000},
// etc
};
Then, in your constructor:
OpeningBook::OpeningBook()
{
for (int i = 0; i < sizeof(DatabaseInitData)/sizeof(DatabaseInitData[0]); i++) {
opening_database_.insert(std::pair<std::string, int>(
DatabaseInitData[i].str,
DatabaseInitData[i].n));
}
}
来源:https://stackoverflow.com/questions/13501257/stack-overflow-with-unordered-map