Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

c++ - How find function work in set and map for string data type in cpp

How find function searches the string in STL set.

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? Does it use like strcmp function?

question from:https://stackoverflow.com/questions/65918737/how-find-function-work-in-set-and-map-for-string-data-type-in-cpp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No it uses the < operator. If a<b is false and a>b is also false then it must be that a equals b.

In fact strcmp cannot be used for std::string comparisons because strcmp treats the nul character ('') as the end of a string, but std::string can contain nul characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...