Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if given int exists in array? [duplicate]

Tags:

c++

arrays

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?

like image 255
rsk82 Avatar asked Oct 10 '13 15:10

rsk82


People also ask

How do I check if an object is an array of duplicates?

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.

How do you check if a number is repeated in an array in C?

for(int j = i + 1; j < length; j++) { if(arr[i] == arr[j]) printf("%d\n", arr[j]); }


2 Answers

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.

like image 56
juanchopanza Avatar answered Oct 04 '22 15:10

juanchopanza


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 } 
like image 27
Zac Howland Avatar answered Oct 04 '22 16:10

Zac Howland