C++ 存储C++;STL集合中的字符串 int main(int argc,char**argv){ 设置s; s、 插入(“hi”); set::iterator it=s.find(“hi”); 如果(it==s.end()){ cout

C++ 存储C++;STL集合中的字符串 int main(int argc,char**argv){ 设置s; s、 插入(“hi”); set::iterator it=s.find(“hi”); 如果(it==s.end()){ cout,c++,string,stl,set,C++,String,Stl,Set,如果条件相反,则应为 int main(int argc, char** argv) { set<string> s; s.insert("hi"); set<string>::iterator it = s.find("hi"); if (it == s.end()) { cout << "Matched." << endl; } else { cout <<

如果
条件相反,则应为

int main(int argc, char** argv) {
    set<string> s;

    s.insert("hi");

    set<string>::iterator it = s.find("hi");

    if (it == s.end()) {
        cout << "Matched." << endl;
    } else {
        cout << "Not matched." << endl;
    }

    return 0;
}
if(it!=s.end()){
~~

cout您可能误解了函数的工作原理。如果其返回值等于s.end(),则并不意味着它匹配。相反,这意味着在到达集合的end迭代器之前,无法找到您要查找的字符串

因此,您应该反转下面给出的if语句

if (it != s.end()) {
       ~~
    cout << "Matched." << endl;
} else {
    cout << "Not matched." << endl;
}   
if(it==s.end()){

cout如果
find(“hi”)
等于
s.end()
这并不意味着它是匹配的。相反,这意味着在到达集合的end迭代器之前无法找到您要查找的字符串。

使用If(it!=s.end())代替If(it==s.end()),因为find将返回一个迭代器到比较等于val(“hi”)的范围内的第一个元素,如果没有匹配的元素,函数将返回last(s.end())。顺便说一句,如果您只需要检查元素是否存在,
count
方法就不那么冗长了。@siri没问题。如果您对目前提供的答案感到满意,请记住选择其中一个作为问题的答案。
if (it == s.end()) {
    cout << "Matched." << endl;
} else {
    cout << "Not matched." << endl;
}   
if (it != s.end()) {
    cout << "Matched." << endl;
} else {
    cout << "Not matched." << endl;
}