简体   繁体   English

如何以无序顺序(C ++)测试一项成员资格?

[英]How does one test item membership in an unordered sequence (C++)?

I've used python for a long time, and I'm just beginning to use C++ 我已经使用python很长时间了,而我才刚刚开始使用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. 在python中,如果有一个集合或一个字典,则使用in关键字相对容易地获得一个布尔值,该布尔值指示特定项目是否在该序列 ie

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? 有没有一种方法可以使cpp中的成员资格测试变得简单而高效,还是您总是必须遍历某些有序序列?

You have functionality like this in std::set and tr1::unordered_set (not yet in C++ standard). 您在std :: set和tr1 :: unordered_set中具有类似的功能(在C ++标准中尚未提供)。

#include <set>
#include <cstdio>

int main() {
     std::set<int> s;
     s.insert(1);        
     s.insert(2);
     s.insert(4);
     if (s.find(4) != s.end())
          puts("4 found!");
     return 0;
}

In reality, if your data set is small, linear search may still be the faster option. 实际上,如果您的数据集很小,则线性搜索可能仍然是更快的选择。

Get to know the C++ Standard Template Library. 了解C ++标准模板库。 The set class (and others) has a find() method that will return an iterator to an item in the set if it exists. set类(和其他set )具有find()方法,该方法将向集合中的项目返回迭代器(如果存在)。

看一下STL提供的容器及其性能特征。

Python's method is not "much more efficient" because you don't know the complexity of in construct. Python的方法并不是“效率更高”,因为您不知道in构造的复杂性。

In C++ there are many methods of storing data. 在C ++中,有许多存储数据的方法。 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 如果使用2、3、4等数字,则可以考虑使用布尔数组,并简单地看一下array[4] == true

template<typename T>
bool contains(const std::set<T>& a, const T& value) {
    return a.find(value) != a.end();
}

if (contains(a, 4)) {
    std::cout << "A contains 4\n";
}

std::find can determine whether or not an element exists in any unordered container or sequence. std::find可以确定元素是否存在于任何无序容器或序列中。 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 than O(N) . 如果序列是无序的,并且没有存储在专门用于查找的专用容器中,那么您做的任何事情都不会比O(N)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM