【发布时间】:2019-07-31 03:26:53
【问题描述】:
我的一项家庭作业有问题,我们需要使用哈希表检测字符串向量中的重复字符串。我的代码可以正常构建和编译,但是当我尝试将重复检测算法的返回向量分配给重复向量时出现分段错误。我试图弄清楚为什么会发生这种情况,但找不到解决方案。我在下面附上了我的代码。
使用哈希表查找重复的功能##
std::vector<std::string>find_duplicates_with_hashtable(std::vector<std::string> & strings) {
std::vector<std::string> dups;
typedef std::unordered_map<std::string, std::string> hashtable;
hashtable table;
for (std::vector<std::string>::iterator i = strings.begin(); i < strings.end(); i++) {
std::unordered_map<std::string, std::string>::const_iterator it = table.find(*i);
if (it != table.end() && (std::find(dups.begin(), dups.end(), *i)) == dups.end()) {
dups = find_duplicates_with_sorting(dups); // line causing the problem
}
table.emplace(*i, *i);
}
return dups;
}
用于检查给定向量中的任何元素是否存在于重复向量中的函数
std::vector<std::string> find_duplicates_with_sorting(std::vector<std::string> & strings) {
std::vector<std::string> dups;
std::sort(strings.begin(), strings.end());
for( unsigned int i = 0; i < strings.size() - 1; ++i ) {
if( strings[i].compare(strings[i+1]) == 0 ) {
std::string found_dup = strings[i];
if( dups.size() == 0 ) {
dups.push_back(found_dup);
}
else
{
std::string last_found_dup = dups[ dups.size() - 1 ];
if( last_found_dup.compare(found_dup) != 0 ) { // Not a dup of a dup
dups.push_back(found_dup);
}
}
}
}
return dups;
}
这是调用哈希表函数的上下文
TEST(BaseHash, SuperShortVector)
{
std::vector<std::string> dups_found;
auto & search_vector = super_short_vector;
auto & known_dups_vector = super_short_vector_dups;
dups_found = find_duplicates_with_hashtable(search_vector);
std::sort(dups_found.begin(), dups_found.end());
std::sort(known_dups_vector.begin(), known_dups_vector.end());
}
导致问题的行由“find_duplicates_with_hashtable”函数中的注释标记
另外,由于这是一项家庭作业,如果有人能解释我做错了什么并给我一个大致的方向来解决问题,我将不胜感激,因为我只是复制粘贴代码不会帮助我学习
对不起,如果代码很糟糕。我无法理解如何使用哈希表。
谢谢你:)
【问题讨论】:
-
您学会如何使用
gdb或类似工具了吗?那将非常有帮助。仅通过查看您不熟悉的代码来查找段错误的来源通常非常耗时 -
@JeffreyCash 我尝试使用 ddd 但我对它非常陌生,所以我不明白为什么会发生段错误。我通过注释掉不同的行并查看哪一行破坏了代码来隔离导致问题的行。