不区分大小写的 std:: 字符串集
如何在 std::set 中进行不区分大小写的插入或搜索字符串?
例如-
std::set<std::string> s;
s.insert("Hello");
s.insert("HELLO"); //not allowed, string already exists.
How do you have a case insensitive insertion Or search of a string in std::set?
For example-
std::set<std::string> s;
s.insert("Hello");
s.insert("HELLO"); //not allowed, string already exists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要定义一个自定义比较器:
如果
strcasecmp
不可用,您可以尝试stricmp
或strcoll
。You need to define a custom comparator:
You may try
stricmp
orstrcoll
ifstrcasecmp
is not available.std::set 提供了提供您自己的比较器的可能性(就像大多数 std 容器一样)。然后您可以执行您喜欢的任何类型的比较。完整示例可在此处获取
std::set offers the possibility of providing your own comparer (as do most std containers). You can then perform any type of comparison you like. Full example is available here
这是一个通用解决方案,也适用于
std::string
之外的其他字符串类型(使用std::wstring
、std::string_view
进行测试) ,char const*
)。基本上任何定义 范围的内容 个字符应该可以工作。这里的关键点是使用
boost::as_literal
允许我们在比较器中统一处理以 null 结尾的字符数组、字符指针和范围。通用代码(“iset.h”):
使用示例(“main.cpp”):
Coliru 现场演示
This is a generic solution that also works with other string types than
std::string
(tested withstd::wstring
,std::string_view
,char const*
). Basically anything that defines a range of characters should work.The key point here is to use
boost::as_literal
that allows us to treat null-terminated character arrays, character pointers and ranges uniformly in the comparator.Generic code ("iset.h"):
Usage example ("main.cpp"):
Live Demo at Coliru
据我所知,这比 stricmp() 更可移植,因为 stricmp() 实际上不是 std 库的一部分,而仅由大多数编译器供应商实现。因此,下面是我自己推出的解决方案。
From what I have read this is more portable than stricmp() because stricmp() is not in fact part of the std library, but only implemented by most compiler vendors. As a result below is my solution to just roll your own.