gpt4 book ai didi

c++ - 如何在搜索中不使用 std::map 的自定义比较功能(map::find)?

转载 作者:行者123 更新时间:2023-11-30 05:34:43 24 4
gpt4 key购买 nike

正如您在我的代码中看到的,lenMap 是一个带有自定义比较函数std::map。这个函数只是检查字符串的长度。

现在当我想搜索一些键(使用 map::find)时, map 仍然使用那个自定义比较函数。

但是当我搜索某个键时,如何强制我的 map 不使用它

代码:

struct CompareByLength : public std::binary_function<string, string, bool>
{
bool operator()(const string& lhs, const string& rhs) const
{
return lhs.length() < rhs.length();
}
};

int main()
{
typedef map<string, string, CompareByLength> lenMap;
lenMap mymap;

mymap["one"] = "one";
mymap["a"] = "a";
mymap["foobar"] = "foobar";

// Now In mymap: [a, one, foobar]

string target = "b";
if (mymap.find(target) == mymap.end())
cout << "Not Found :) !";
else
cout << "Found :( !"; // I don't want to reach here because of "a" item !

return 0;
}

最佳答案

map 本身不提供这样的操作。比较仿函数的想法是创建一个内部排序以加快查找速度,因此元素实际上是根据您的仿函数排序的。

如果您需要以不同的方式搜索元素,您可以使用 STL 算法 std::find_if()(具有线性时间复杂度)或创建第二个使用另一个映射的映射比较仿函数。

在您的特定示例中,由于您似乎只对字符串的长度感兴趣,因此您应该使用长度(std::size_t 类型)而不是字符串本身作为键。

顺便说一下,std::binary_function 不需要作为基类。从 C++11 开始,它甚至被弃用,参见 here例如。

关于c++ - 如何在搜索中不使用 std::map 的自定义比较功能(map::find)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34122175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com