簡體   English   中英

如何在 cpp 中查找 function 和 map 的字符串數據類型

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

find function 如何在 STL 集合中搜索字符串。

請參閱下面的代碼片段

#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;
}

在這里,我不確定 find() 方法如何在內部工作,它如何檢查字符串? 它是否像 strcmp function 一樣使用?

不,它使用<運算符。 如果a<b為假且a>b也為假,則 a 一定等於 b。

實際上strcmp不能用於std::string比較,因為strcmp將 nul 字符 ( '\0' ) 視為字符串的結尾,但std::string可以包含 nul 字符。

std::set ,無論它是否包含std::string ,都使用比較器來搜索集合。 默認比較器是std::less ,它使用<運算符進行比較。

"Hello"被隱式轉換為std::string ,因此這會導致重載<運算符比較std::string ,以影響您的find() 因為 C++ std::string可以包含'\0' ,所以不能使用 C 庫的strcmp function。

在 C++14 及更高版本中,可以將比較器覆蓋為std::less<void>透明重載。 這導致(通過一系列事件)使用其他直接比較std::stringconst char *<重載,避免了僅為了執行find()的目的而構建臨時std::string object . 在 C++20 中,以及以后的情況下,這是使用<=>重載實現的。

不幸的是,您必須明確指定std::less<void>比較器,因為默認set的比較器仍然是std::less<Key>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM