问题描述
我想创建一个,以便我可以检查某个字是否在集合中使用set :: find
I want to create one so that I could check whether a certain word is in the set using set::find
但是,C字符串是指针,所以默认情况下,集合将通过指针值进行比较。为了正确地运行,它必须取消引用它们并比较字符串。
However, C-strings are pointers, so the set would compare them by the pointer values by default. To function correctly, it would have to dereference them and compare the strings.
我可以传递构造函数作为比较器的strcmp()函数的指针,不是我想要它的工作。我可能想检查的词可能是较长字符串的一部分,并且我不想创建一个新的字符串,由于性能问题。如果没有为集合,我会使用strncmp(a1,a2,3)来检查前3个字母。事实上,3可能是最长的时间,所以我很好与第三个参数常数。
I could just pass the constructor a pointer to the strcmp() function as a comparator, but this is not exactly how I want it to work. The word I might want to check could be part of a longer string, and I don't want to create a new string due to performance concerns. If there weren't for the set, I would use strncmp(a1, a2, 3) to check the first 3 letters. In fact, 3 is probably the longest it could go, so I'm fine with having the third argument constant.
有一种方法来构造一个集,将比较它的元素通过调用strncmp()?非常感谢代码示例。
Is there a way to construct a set that would compare its elements by calling strncmp()? Code samples would be greatly appreciated.
这里是我想要做的伪代码:
Here's pseudocode for what I want to do:
bool WordInSet (string, set, length)
{
for (each word in set)
{
if strncmp(string, word, length) == 0
return true;
}
return false;
}
但我更喜欢使用标准库函数来实现它。 p>
But I'd prefer to implement it using the standard library functions.
推荐答案
创建包装函数:
bool myCompare(const char * lhs, const char * rhs)
{
return strncmp(lhs, rhs, 3) < 0;
}
这篇关于C ++:C字符串集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!