0
我们有一个C++数组对象和一个值。我们要控制这个值在数组中还是不在数组中。我们如何做到这一点?在C++中实现python的'if X in List'
我们有一个C++数组对象和一个值。我们要控制这个值在数组中还是不在数组中。我们如何做到这一点?在C++中实现python的'if X in List'
使用std::find()
#include <array>
#include <iostream>
#include <algorithm>
int main()
{
std::array<int, 5> a1 { { 2, 3, 5, 7, 11 } };
std::cout << "8 is in a1 ? "
<< (a1.cend() != std::find(a1.cbegin(), a1.cend(), 8)) << std::endl;
std::cout << "7 is in a1 ? "
<< (a1.cend() != std::find(a1.cbegin(), a1.cend(), 7)) << std::endl;
return 0;
}
可与每一个执行容器或支持begin()
和end()
(或更好,cbegin()
和cend()
)