gpt4 book ai didi

c++ - 在 STL 集中存储 C++ 字符串

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:57 24 4
gpt4 key购买 nike

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 比较器对象是否不适用于字符串?如果不是,那么如何为字符串分配正确的比较器对象?

最佳答案

您可能误解了如何 find()功能有效。如果它的返回值等于s.end(),并不代表匹配成功。反之,则表示在到达集合的末尾迭代器之前,找不到要查找的字符串。

因此您应该反转 if 语句,如下所示。

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

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

关于c++ - 在 STL 集中存储 C++ 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37020868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com