简体   繁体   English

如何在 cpp 中查找 function 和 map 的字符串数据类型

[英]How find function work in set and map for string data type in cpp

How find function searches the string in STL set. find function 如何在 STL 集合中搜索字符串。

See the below code snippet请参阅下面的代码片段

#include<set>
#include<string>
#include<iostream>

using namespace std;

int main()
{
    set<string> myset{"Hello","Hi"};
    if(myset.find("Hello") != myset.end()){
        cout<<"Find"<<endl;
    }else{
        cout<<" Didn't find"<<endl;
    }
    return 0;
}

Here, I am not sure how find() method work internally, how it checks the string?在这里,我不确定 find() 方法如何在内部工作,它如何检查字符串? Does it use like strcmp function?它是否像 strcmp function 一样使用?

No it uses the < operator.不,它使用<运算符。 If a<b is false and a>b is also false then it must be that a equals b.如果a<b为假且a>b也为假,则 a 一定等于 b。

In fact strcmp cannot be used for std::string comparisons because strcmp treats the nul character ( '\0' ) as the end of a string, but std::string can contain nul characters.实际上strcmp不能用于std::string比较,因为strcmp将 nul 字符 ( '\0' ) 视为字符串的结尾,但std::string可以包含 nul 字符。

std::set , whether it contains std::string or not, uses a comparator to search the set. std::set ,无论它是否包含std::string ,都使用比较器来搜索集合。 The default comparator isstd::less , which uses the < operator for comparison.默认比较器是std::less ,它使用<运算符进行比较。

"Hello" gets implicitly converted to a std::string , so this results in the overloaded < operator comparing std::string s, to effect your find() . "Hello"被隐式转换为std::string ,因此这会导致重载<运算符比较std::string ,以影响您的find() Because C++ std::string can contain '\0' , this cannot use the C library's strcmp function.因为 C++ std::string可以包含'\0' ,所以不能使用 C 库的strcmp function。

In C++14 and later one can override the comparator to the std::less<void> transparent overload.在 C++14 及更高版本中,可以将比较器覆盖为std::less<void>透明重载。 This results (via a sequence of events) of employing other < overloads that compare a std::string with a const char * directly, avoiding the need to construct a temporary std::string object solely for the purpose of doing the find() .这导致(通过一系列事件)使用其他直接比较std::stringconst char *<重载,避免了仅为了执行find()的目的而构建临时std::string object . In C++20, and going forward this is implemented using the <=> overload.在 C++20 中,以及以后的情况下,这是使用<=>重载实现的。

Unfortunately you have to explicitly specify the std::less<void> comparator, since the default set comparator is still std::less<Key> .不幸的是,您必须明确指定std::less<void>比较器,因为默认set的比较器仍然是std::less<Key>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM