C++ 是否有一个相当于;在;C++;?

C++ 是否有一个相当于;在;C++;?,c++,python,C++,Python,最近我只讨论了Python编程,它们是一个非常有用的内置函数,名为“'in” “in”允许您访问变量中的所有元素 比如, def main(): y = ["Yes", "yes", "YES",] n = ["No", "no", "NO"] print "yes or no?\n" response = raw_input() if response in y: print "Wonderful, your response was ", response, "\n" exi

最近我只讨论了Python编程,它们是一个非常有用的内置函数,名为“'in”

“in”允许您访问变量中的所有元素

比如,

def main():
y = ["Yes", "yes", "YES",]
n = ["No", "no", "NO"]
print "yes or no?\n"
response = raw_input()
if response in y:
    print "Wonderful, your response was ", response, "\n"
    exit(0)
if response in n:
    print "Alas, your response was ", response, "\n"
    exit(0)
else:
    print "Message not read; please attempt again.\n"
    main()

main()
如您所见,它使用“in”函数检查字典中的字符串


我想知道C++ C++库中是否有一个等价的函数?< /p> 如果你使用C++向量:

if (std::find(vector.begin(), vector.end(), yourItem)!=vector.end() )
....
相当于

if yourItem in vector:

如果你使用C++向量:

if (std::find(vector.begin(), vector.end(), yourItem)!=vector.end() )
....
相当于

if yourItem in vector:

许多
std
容器都有一个名为
find
的函数。但是,为了获得实际性能,您需要使用
std::unordered_set
(C++11),因为它在底层实现中使用了一个哈希表,使得
find()
在固定时间内操作,而其他容器在线性时间内操作。

许多
std
容器都有一个名为
find
的函数。但是,为了获得实际性能,您需要使用
std::unordered_set
(C++11),因为它在底层实现中使用哈希表,使得
find()
在固定时间内操作,而其他容器在线性时间内操作。

有函数

std::find(std::begin(a), std::end(a), needle) != std::end(a)
其中
a
是数组或
std::vector
std::list


但是在这种情况下,您也可以使用
std::set
std::unordered\u set
(如果有很多元素,您应该这样做)

有功能

std::find(std::begin(a), std::end(a), needle) != std::end(a)
其中
a
是数组或
std::vector
std::list


但是在这种情况下,您也可以使用
std::set
std::unordered\u set
(如果有很多元素,您应该这样做)


除了前面提到的其他方法之外,还有一种方法可能命名不好。如果元素存在,则返回true,否则返回false。您需要一个排序容器来使用它


bool found=std::binary_search(std::begin(container),std::end(container),element);

除了前面提到的其他方法之外,还有一些可能命名不好的方法。如果元素存在,则返回true;否则返回false。您需要一个已排序的容器来使用它


boolfound=std::binary\u搜索(std::begin(容器)、std::end(容器)、元素)如果你使用C++和问题,请重新修改C++,如果我错了,请重新编辑并更改到C。代码:STD::unOrdEdEDSET/<代码>可能有这个。改为C++,因为你使用C++和问题。如果我是错误的,请重新编辑并更改到C。Python列表查找(如OP示例中所示)也是一种线性搜索。(要让Python使用哈希表,您需要将内容放入其字典类型中。)我认为对于长度不超过3的3个元素(如示例中所示),差异并不大。请注意,Python列表查找(如OP示例中所示)也是一种线性搜索。(为了让Python使用哈希表,您需要将内容放入它的字典类型中。)我认为对于长度不超过3的3个元素,如示例中所示,
std::binary_search()
函数只有在容器先排序的情况下才会成功!@DietrichEpp在答案中已经得到了这一点。我想我会将其加粗以便于澄清。只有在容器先排序的情况下,
std::binary_search()
函数才会成功!@DietrichEpp在答案中已经得到了这一点。我想将其加粗以便于澄清。