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?
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
for(int j = i + 1; j < length; j++) { if(arr[i] == arr[j]) printf("%d\n", arr[j]); }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With