如何测试无序序列 (C++) 中的项目成员资格?
我已经使用python很长时间了,并且刚刚开始使用C++
在python中,如果有一个集合或字典,那么相对容易获得一个布尔值来指示特定项目是否在该序列中使用 in 关键字。 也就是说,
a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"
它比这样做更有效:
a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"
有没有一种方法可以使 cpp 中的成员资格测试变得简单而高效,或者您是否总是必须迭代某些有序序列?
I've used python for a long time, and I'm just beginning to use C++
In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.
a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"
it's much more efficient than doing this:
a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"
is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您在 std::set 和 tr1::unordered_set (不是但在 C++ 标准中)。
实际上,如果您的数据集很小,线性搜索可能仍然是更快的选择。
You have functionality like this in std::set and tr1::unordered_set (not yet in C++ standard).
In reality, if your data set is small, linear search may still be the faster option.
了解 C++ 标准模板库。
set
类(和其他类)有一个find()
方法,该方法将返回指向集合中某个项目(如果存在)的迭代器。Get to know the C++ Standard Template Library. The
set
class (and others) has afind()
method that will return an iterator to an item in the set if it exists.查看 STL 提供的容器及其性能特征。
Take a look at the containers offered by STL and their performance characteristics.
Python 的方法并不是“高效得多”,因为你不知道
in
构造的复杂性。C++中有很多存储数据的方法。二叉树最适合搜索。
如果您使用 2、3、4 等数字,您可以考虑使用布尔数组,并简单地查看是否
array[4] == true
Python's method is not "much more efficient" because you don't know the complexity of
in
construct.In C++ there are many methods of storing data. Binary trees are best for searching.
If you work with numbers like 2,3,4 etc, you may consider having an array of bools, and simply see if
array[4] == true
std::find
可以判断某个元素是否存在存在于任何无序容器或序列中。如果序列是无序的并且没有存储在为查找而设计的专用容器中,那么您不可能做得比O(N)
更好。std::find
can determine whether or not an element exists in any unordered container or sequence. If the sequence is unordered and not stored in a specialized container designed for lookups, it's unlikely you're going to do any better thanO(N)
.