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?
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.
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;
Try this
#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;
}
int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));
Returns an invalid index (length of the array) if not found.
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