【发布时间】:2013-10-10 15:06:40
【问题描述】:
例如,我有这个数组:
int myArray[] = { 3, 6, 8, 33 };
如何检查给定的变量 x 是否在其中?
我必须编写自己的函数并循环数组,还是在现代 c++ 中相当于 PHP 中的 in_array?
【问题讨论】:
-
看
std::find的例子。
例如,我有这个数组:
int myArray[] = { 3, 6, 8, 33 };
如何检查给定的变量 x 是否在其中?
我必须编写自己的函数并循环数组,还是在现代 c++ 中相当于 PHP 中的 in_array?
【问题讨论】:
std::find的例子。
您可以为此使用std::find:
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
int main ()
{
int a[] = {3, 6, 8, 33};
int x = 8;
bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}
std::find 将迭代器返回到 x 的第一次出现,或者如果未找到 x,则返回到范围末尾的迭代器。
【讨论】:
bool exists = std::any_of(std::begin(array), std::end(array), [&](int i) { return i == x; });
std::find 如果您不在 C++ 11 上,那很好。然后std:begin 和 std:end 仅适用于 C++ 11。
int *squaresPlayerMarked = new int[5](); int x = 8; bool exists = std::find(std::begin(squaresPlayerMarked), std::end(a), squaresPlayerMarked) != std::end(a); std::cout << exists;
squaresPlayerMarked + 5。跨度>
我认为您正在寻找std::any_of,它将返回真/假答案以检测元素是否在容器中(数组、向量、双端队列等)
int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
return i == val;
});
如果您想知道元素在哪里,std::find 将返回一个迭代器,指向与您提供的任何条件(或您给它的谓词)匹配的第一个元素。
int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
// not found
}
else
{
// found
}
【讨论】:
试试这个
#include <iostream>
#include <algorithm>
int main () {
int myArray[] = { 3 ,6 ,8, 33 };
int x = 8;
if (std::any_of(std::begin(myArray), std::end(myArray), [=](int n){return n == x;})) {
std::cout << "found match/" << std::endl;
}
return 0;
}
【讨论】:
您几乎不必用 C++ 编写自己的循环。在这里,您可以使用std::find。
const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
std::cout << "Found.\n"
}
else
{
std::cout << "Not found.\n";
}
std::end 需要 C++11。没有它,您可以通过以下方式找到数组中的元素数:
const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);
...结尾是:
int* end = myArray + numElements;
【讨论】:
int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));
如果未找到,则返回无效索引(数组的长度)。
【讨论】:
您确实需要遍历它。在处理原始类型数组时,C++ 没有实现任何更简单的方法。
【讨论】:
std::find,std::find_first_of,std::any_of。它们都实现了循环,但是语言已经为你提供了它们(所以你不需要自己编写)。在 C++ 中,大多数时候您很少需要编写自己的循环。
std::(c)(r)(begin|end) 的重载,以便它们可以通过使用统一语法的算法进行处理。甚至在那些首次亮相之前,指向(或者,当然是过去的)原始数组的指针就可以用作迭代器。就像,迭代器是指针的超集,所以当然。