将字符串变量与一组字符串常量进行比较的最佳方法是什么?
if
语句看起来太尴尬了,因为我需要增加常量数量的可能性。 很抱歉让您误以为“常数”而不是我的意思。
if
statement looks too awkward, because i need a possibility to increase the number of constatnts.
Sorry for leading you into delusion by that "constant" instead of what i meant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将所有常量添加到 std::set 然后您可以检查该集合是否包含您的字符串
Add all your constants to a std::set then you can check if the set contains your string with
取决于你是否关心性能。
如果没有,那么最简单的代码可能是将各种字符串放入数组中(如果您想在运行时增加常量的数量,则将其放入向量中)。 对于少量字符串来说,这也将相当快:
然后:
或者:
[警告:我还没有测试上面的代码,并且我已经多次得到签名错误......]
如果你确实关心性能,并且有合理数量的字符串,那么一个快速选择就是 Trie。 但这需要付出很大的努力,因为标准 C++ 库中没有这样的库。 获得很多好处。
您可以使用排序的数组/向量、使用
std::binary_search
: ... 进行搜索或使用std::set
来 但是,除非您在运行时更改字符串集,否则使用二分搜索的集合比使用排序数组没有任何优势,并且必须用代码填充集合(或向量),而数组可以静态初始化。 我认为 C++0x 会通过集合的初始值设定项列表来改进一些事情。Depends whether you care about performance.
If not, then the simplest code is probably to put the various strings in an array (or vector if you mean you want to increase the number of constants at run time). This will also be pretty fast for a small number of strings:
Then either:
Or:
[Warning: I haven't tested the above code, and I've got the signatures wrong several times already...]
If you do care about performance, and there are a reasonable number of strings, then one quick option would be something like a Trie. But that's a lot of effort since there isn't one in the standard C++ library. You can get much of the benefit either using a sorted array/vector, searched with
std::binary_search
:... or use a
std::set
. But unless you're changing the set of strings at runtime, there is no advantage to using a set over a sorted array with binary search, and a set (or vector) has to be filled in with code whereas an array can be statically initialized. I think C++0x will improve things, with initializer lists for collections.将要比较的字符串放入静态向量或集合中,然后使用 std::find 算法。
Put the strings to be compared in a static vector or set and then use std::find algorithm.
技术上最好的解决方案是:根据您的字符串常量集构建一个“完美的哈希函数”,这样以后在哈希过程中就不会发生冲突。
The technically best solution is: build a 'perfect hash function' tailored to your set of string constants, so later there are no collisions during hashing.
或者使用 std::set。
Or use a std::set.