【发布时间】:2022-01-05 01:37:15
【问题描述】:
我有一个任务:从 EnglishWords.txt 中实现 60.000 个英文单词,然后对其进行排序和搜索。
我已经使用自定义 MergeSort 和 find_if STL 完成了排序和线性搜索,但是当我尝试使用其他向量 STL 时,例如 upper_bound、lower_bound、binary_search,它会导致以下一些问题:
- 如果运行 lower_bound 函数,它不会返回与“手动搜索”函数相同的“索引”。
- 不能将“MatchString”(我的重载运算符)用于 lower_bound 和 binary_search ST 或其他向量 STL 并返回 C2672 和 C2893 代码。
- 另外,有人可以给我一些关于按字母“排序”的建议吗?
我的完整代码在https://onlinegdb.com/l4pfS9pYJ,请点击“Fork this”编辑代码。
一些额外的要求和概念。
- 我是 OOP 新手,因此请向我展示一些建议,以提高我的代码编写技能。
- 不要使用 STL sort(),自己写。
- 必须将所有排序、搜索和工作功能放到 FastDictionary 中。
下面是我的重载运算符和有问题的函数。
void searchmanually(vector<Dictionary> list, string value)
{
vector<Dictionary>::iterator it;
it = find_if(list.begin(), list.end(), FastDictionary::MatchString(value));
if (it != list.end())
{
auto idx = distance(list.begin(), it);
cout << "Index = " << idx << endl;
}
else
{
cout << "Can not find the value !." << endl;
}
}
void binary_search_find_index(vector<Dictionary> list, string value)
{
vector<Dictionary>::iterator it1;
it1 = lower_bound(list.begin(), list.end(), FastDictionary::MatchString(value));
if (it1 != list.end())
{
auto idx1 = distance(list.begin(), it1);
cout << "Index = " << idx1 << endl;
}
else
{
cout << "Can not find the value !." << endl;
}
}
struct MatchString
{
private:
const std::string& s_;
public:
MatchString(const std::string& s) : s_(s) {}
bool operator()(const Dictionary& obj) const
{
return obj._word == s_;
}
friend bool operator<(const Dictionary& obj, const MatchString &str)
{
return obj._word < str.s_;
}
friend bool operator>(const Dictionary& obj, const MatchString &str)
{
return obj._word > str.s_;
}
};
因为我认为我的“错误”有点连锁,所以我尝试尽可能详细地描述错误。
非常感谢。
【问题讨论】:
-
首先欢迎来到 Stack Overflow。请阅读the help pages,接受SO tour,阅读How to Ask,以及this question checklist。最后,请每个问题只发布一个问题。您有多个不相关的问题。
-
那么关于搜索,您确定排序正常吗?如果您采用更小的输入集(或者更好的是硬编码一小组字符串),排序是否能正确处理小写字母和大写字母?
-
另外,
MatchString保存对std::string对象的引用。当对象用于排序和匹配时,它会在整个程序中一直存在吗?请尝试创建minimal reproducible example 向我们展示。 -
您要排序的顺序与
lower_bound期望的顺序不同。再次检查您的排序 - 它真的按字母排序吗? -
另外,
lower_bound想要一个排序谓词,例如“小于”,而不是相等。