【发布时间】:2016-05-04 07:15:10
【问题描述】:
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;
}
输出显示不匹配。
我想存储一组唯一的字符串。但是 set 中的 find() 没有找到我已经插入的字符串。默认的 less 比较器对象是否不适用于字符串?如果不是,那么如何为字符串分配正确的比较器对象?
【问题讨论】:
-
而不是 if (it == s.end()) 使用 if (it != s.end()) ,因为 find 将返回一个迭代器到范围内的第一个元素比较等于 val ("hi"),如果没有元素匹配,函数返回 last (s.end())。
-
顺便说一句,如果您只需要检查一个元素是否存在,
count方法就不会那么冗长了。