提问人:Nathan Allie 提问时间:11/8/2023 最后编辑:genpfaultNathan Allie 更新时间:11/8/2023 访问量:62
无法访问地址 0x4 (unordered_map) 处的内存
Cannot access memory at address 0x4 (unordered_map)
问:
我正在编写一个拼写检查器,它使用 Levenshtein Distance 算法和字典的哈希映射。此函数旨在将一个字符串作为输入,将其与整个字典进行比较,然后输出一个具有最小 lev 距离的字符串。
std::string SpellChecker::levenshteinDist(std::string word)
{
std::string minDistStr;
int minDist = INT_MAX;
//convert to char[]
char a[word.length()];
strcpy(a, word.c_str());
for(auto i: dictionary)
{
std::string bString = i.first;
char b[i.first.length()];
strcpy(b, i.first.c_str());
int aLength = word.length();
int bLength = i.first.length();
int grid[aLength][bLength] = {};
for(int col = 0; col < aLength + 1; col++){
for(int row = 0; row < bLength + 1; row++){
if(col == 0)
{
//Initialize first column
grid[0][row] = row;
}
else if(row == 0)
{
//initialize first row
grid[col][0] = col;
}
else if(a[col-1] == b[row-1])
{
grid[col][row] = grid[col-1][row-1];
}
else
{
//Find cost of each operation
int insert = grid[col-1][row];
int replace = grid[col-1][row-1];
int del = grid[col][row-1];
// Minimum operation is recorded
grid[col][row] = 1 + std::min(std::min(insert, replace), del);
}
}
}
if(grid[aLength][bLength] < minDist)
{
minDist = grid[aLength][bLength];
minDistStr = bString;
}
}
return minDistStr;
}
该函数适用于前几个字典项,但最终遇到异常,我的调试器不显示 bString 的值,而是显示 .下面是 SpellChecker 的类声明<error: Cannot access memory at address 0x4>
class SpellChecker{
private:
std::unordered_map<std::string, bool> dictionary;
public:
SpellChecker(std::string fileName);
bool search(std::string word);
std::vector<std::string> similarWords(std::string word);
std::string levenshteinDist(std::string word);
};
SpellChecker::SpellChecker(std::string fileName)
{
std::ifstream dictFile;
dictFile.open(fileName);
std::string pipeStr;
while (dictFile)
{
dictFile >> pipeStr;
dictionary[pipeStr] = true;
}
}
词典是一个文本文件,其中包含由换行符分隔的单个单词。为什么会这样?
答: 暂无答案
评论
char b[i.first.length()];
-pedantic-errors
a
b
char
nullptr
std::vector
std::string
std::string
char