For example, I have this array:
int myArray[] = { 3, 6, 8, 33 };
How to check if given variable x is in it?
Do I have to write my own function and loop the array, or is there in modern c++ equivalent to in_array in PHP?
You can use std::find for this:
#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 returns an iterator to the first occurrence of x, or an iterator to one-past the end of the range if x is not found.
bool exists = std::any_of(std::begin(array), std::end(array), [&](int i) { return i == x; });std::find is nice if you aren't on C++ 11. Then again std:begin and std:end are C++ 11 only.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.I think you are looking for std::any_of, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)
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;
});
If you want to know where the element is, std::find will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).
int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
// not found
}
else
{
// found
}
You almost never have to write your own loops in C++. Here, you can use 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 requires C++11. Without it, you can find the number of elements in the array with:
const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);
...and the end with:
int* end = myArray + numElements;
You do need to loop through it. C++ does not implement any simpler way to do this when you are dealing with primitive type arrays.
also see this answer: C++ check if element exists in array
std::find, std::find_first_of, std::any_of. They all implement loops, but the language has provided them for you (so you do not need to write your own). In C++, most of the time you will rarely have to write your own loop.std::(c)(r)(begin|end) for raw arrays so that they can be processed by algorithms using unified syntax. Even before those debuted, pointers into (or, of course, one-past-the-end of) raw arrays could be used as iterators. Like, iterators are a superset of pointers, so of course.
std::find.