Is element in array: true/false

Very basic question: Is there a way to return a TRUE/FALSE if an element is in an array or not?

Say I have int myArray [] = {x, y, z,}; where x-z are integers.

Is there a function (call it IsInArray) that would do the following:
IsInArray (myArray, x) returns TRUE but
IsInArray (myArray, w) returns FALSE (w being an integer not in myArray)?

I don't need to know the index just a yes or no although I suppose something like IsNumber (array index for element) would work for my purpose.

Thanks in advance :)
Last edited on
The find algorithm might be what you are looking for, check if the returned iterator is valid or not.
http://www.cplusplus.com/reference/algorithm/find/
Hello GeorgeSDG,

I do not believe there is a STL function "isInArray" that I know of unless this is a function that you write.

As Furry Guy mentioned there are several functions in the "algorithm" header file that might work.

I was playing around and this might work also:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// <--- Most comon includes.
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
//#include <chrono>
//#include <thread>

constexpr size_t MAXSIZE{ 8 };

bool isInArray(int myArray[], int numToFind);

int main()
{
	int numToFind{};
	int myArray[MAXSIZE] = { 1, 2, 3, 4, 5, 6, 7, 8 };

	std::cout << "\n Enter number to find: ";

	while (!(std::cin >> numToFind))
	{
		std::cout << "\n    Invalid Entry! must be a number.\n";

		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.

		std::cout << "\n Enter number to find: ";
	}


	if(isInArray(myArray, numToFind))
		std::cout<<"\n  Number found.\n";
	else
		std::cout << "\n  Number not found.\n";


	// <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
	// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue: ";
	std::cin.get();

	return 0;  // <--- Not required, but makes a good break point.
}

bool isInArray(int myArray[], int numToFind)
{
	for (int index = 0; index < MAXSIZE; index++)
	{
		if (myArray[index] == numToFind)
			return true;
	}

	return false;
}



Andy
find and binary search both exist (if its sorted, you can bin search). There are ways to do it better if you have enough data and search it enough times that a linear crawl is too slow, but they are not built-in one liners.
Custom functions using std::find to return true/false whether an element is in an array or a std::vector:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <algorithm>
#include <vector>

bool IsInArray(int*, int, int);
bool IsInVector(std::vector<int>&, int);

int main()
{
   const int num_to_find { 30 };

   int myints[] = { 10, 20, 30, 40 };

   std::cout << "Array element was ";

   if (!IsInArray(myints, 4, num_to_find))
   {
      std::cout << "NOT ";
   }
   std::cout << "found.\n";

   std::vector<int> myvector(myints, myints + 4);

   std::cout << "Vector element was ";

   if (!IsInVector(myvector, num_to_find))
   {
      std::cout << "NOT ";
   }
   std::cout << "found.\n";

}

bool IsInArray(int* arr, int size, int num)
{
   int* p = std::find(arr, arr + size, num);

   if (p != arr + size)
   {
      return true;
   }

   return false;
}

bool IsInVector(std::vector<int>& vec, int num)
{
   std::vector<int>::iterator it = std::find(vec.begin(), vec.end(), num);

   if (it != vec.end())
   {
      return true;
   }

   return false;
}

A 5 minute code mashup that could be neater. Especially using templates to pass the array or vector so the actual type can vary.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

template <typename T> bool isInArray( T* arr, int size, T value )
{
   return find( arr, arr + size, value ) != arr + size;
}

template <typename C, typename T> bool isInArray( const C &cont, T value )
{
   return find( cont.begin(), cont.end(), value ) != cont.end();
}

int main()
{
   int A[] = { 3, 5, 9, 12 };
   vector<int> V = { 3, 5, 9, 12 };

   int N = sizeof A / sizeof A[0];
   for ( int i = 0; i < 10; i++ ) cout << i << ( isInArray( A, N, i ) ? " is " : " is not " ) << "in the array\n";
   cout << '\n';
   for ( int i = 0; i < 10; i++ ) cout << i << ( isInArray( V, i    ) ? " is " : " is not " ) << "in the array\n";
}

Last edited on
When I said template this is more of what I had in mind:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <algorithm>
#include <vector>

template <typename T, size_t N>
bool IsInArray(T(&)[N], T);

template <typename T>
bool IsInVector(std::vector<T>&, T);

int main()
{
   const int num_to_find { 30 };

   int myints[] { 10, 20, 30, 40 };

   std::cout << "Array element was ";

   if (!IsInArray(myints, num_to_find))
   {
      std::cout << "NOT ";
   }
   std::cout << "found.\n";

   std::vector<int> myvector(myints, myints + 4);

   std::cout << "Vector element was ";

   if (!IsInVector(myvector, num_to_find))
   {
      std::cout << "NOT ";
   }
   std::cout << "found.\n";

}

template <typename T, size_t N>
bool IsInArray(T(&arr)[N], T to_find)
{
   T* p { std::find(arr, arr + N, to_find) };

   if (p != arr + N)
   {
      return true;
   }

   return false;
}

template <typename T>
bool IsInVector(std::vector<T>& vec, T to_find)
{
   // let the compiler figure out the type of the iterator
   auto it { std::find(vec.begin(), vec.end(), to_find) };

   if (it != vec.end())
   {
      return true;
   }

   return false;
}

Now passing a regular array into a function doesn't need the additional array size parameter passed into the function as is normally used with a non-template function.
Thank you everyone for your suggestions; and thank you, too, for taking the time to help out a c++ noob. I have in the past been too quick to write customised code for when I come up with a problem like this. Then, having spent too much time on it, someone comes along and says, “You could have just used function X”. I’m trying to get my c++ learning off on the right foot and use inbuilt functionality first before I try to reinvent the wheel. Thanks again :)
Heh.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>



// MEGA-simplified version

#include <algorithm>
#include <iterator>

template <typename X, typename XS>
bool operator | ( const X& x, const XS& xs )
{
  using  std::begin;
  using  std::end;
  return std::find( begin( xs ), end( xs ), x ) != end( xs );
}

// Here's the array version, since everyone else included theirs...
template <typename X, typename XS, std::size_t N>
bool operator | ( const X& x, const XS (&xs)[N] )
{
  return std::find( std::begin( xs ), std::end( xs ), x ) != std::end( xs );
}

// (Don't look at me!)
#define in |
#define ni &



int main()
{
  std::string x;
  {
    std::cout << "x? ";
    (std::cin >> x).ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
  }
  
  std::vector <std::string> xs;
  {
    std::cout << "xs? ";
    std::string s;
    getline( std::cin >> std::ws, s );
    std::istringstream ss( s );
    while (ss >> s) xs.emplace_back( s );
  }
  
  //--------------------------------------------------------------------------------
  std::cout << std::boolalpha << "x in xs = " << (x in xs) << "\n";
  //--------------------------------------------------------------------------------
}
x? yellow
xs? word from the big yellow bird
x in xs = true
x? 74
xs? 2 3 5 7 11 42
x in xs = false

Muah hah hah hah hah...
Last edited on
Last edited on
All right then Fry...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <cmath>
#include <functional>
#include <iostream>
#include <limits>
#include <locale>
#include <sstream>
#include <string>
#include <vector>

// A probabilistic Bloom Filter for your reading pleasure

template <typename Key, typename Hash = std::hash <Key> >
struct bloom
{
  int k;
  std::vector <bool> bits;
  
  bloom( int n, double p = 0.05 )
  {
    using std::log;
    int m = -n * log( p ) / (log(2) * log(2));
    k = m * log(2) / n;
    bits.resize( m );
  }
  
  int index( int n, std::size_t h ) const
  {
    return ((h & 0xFFFF) + n * (h >> 16)) % bits.size();
  }
  
  void add( Key key )
  {
    auto h = std::hash <Key> {} ( key );
    for (int n = 0; n < k; n++)
      bits[index( n, h )] = true;
  }
  
  bool contains( Key key ) const
  {
    auto h = std::hash <Key> {} ( key );
    for (int n = 0; n < k; n++)
      if (!bits[index( n, h )])
        return false;
    return true;
  }
};

// Plus an awesomer way to bool → alpha

struct boolalpha : public std::numpunct <char>
{
  std::string truename, falsename;
  boolalpha( 
    const std::string& truename  = "true", 
    const std::string& falsename = "false" )
  : truename{truename}, falsename{falsename} { }
  protected: std::string do_truename () const override { return truename; }
  protected: std::string do_falsename() const override { return falsename; }
};

std::ostream& operator << ( std::ostream& outs, const boolalpha& bns )
{
  outs << std::boolalpha;
  outs.imbue( { outs.getloc(), new boolalpha( bns.truename, bns.falsename ) } );
  return outs;
}

// Enjoy!

int main()
{
  std::string x;
  {
    std::cout << "x? ";
    (std::cin >> x).ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
  }
  
  bloom <std::string> xs( 100 );
  {
    std::cout << "xs? ";
    std::string s;
    getline( std::cin >> std::ws, s );
    std::istringstream ss( s );
    while (ss >> s) xs.add( s );
  }
  
  //------------------------------------------------------------------------------------------
  std::cout << boolalpha( "maybe", "no" ) << "x in xs = " << xs.contains( x ) << "\n";
  //------------------------------------------------------------------------------------------
}

:O)
Last edited on
Topic archived. No new replies allowed.