我想创建一个,以便我可以使用set :: find检查某个单词是否在集合中
但是,C字符串是指针,因此默认情况下,该集合将通过指针值对它们进行比较.要正常运行,必须取消引用它们并比较字符串.
我可以将构造函数指向strcmp()函数作为比较器,但这并不是我想要的工作方式.我可能要检查的单词可能是更长字符串的一部分,我不想因为性能问题而创建新字符串.如果没有集合,我会使用strncmp(a1,a2,3)来检查前3个字母.事实上,3可能是最长的,所以我可以将第三个参数保持不变.
有没有办法构建一个通过调用strncmp()来比较其元素的集合?我们非常感谢代码示例.
这是我想要做的伪代码:
bool WordInSet (string, set, length)
{
for (each word in set)
{
if strncmp(string, word, length) == 0
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
但我更喜欢使用标准库函数来实现它.
您可以创建比较器函数对象.
struct set_object {
bool operator()(const char* first, const char* second) {
return strncmp(first, second, 3);
}
};
Run Code Online (Sandbox Code Playgroud)
std::set<const char*, set_object> c_string_set;
然而,制作一套更简单,更可靠std::strings
.