Check all values of array in one

Hello

I need to check if the value of array A, also exists somewhere in array B.

Pseudo code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;
int main() {

int a[50] = {
1,
6
};
int b[50] = {
4,
8,
1,
9
};

for (int i = 0; i < 10; i++) {
if (a[i] == b[0..5]) {
cout << a[i] << " Exists somewhere"<<endl;
}
}

}


Just Pseudo of course. :)

Possible to do this?

Thanks for reading,
Niely
Is it for single value? If so, a simple linear search would suffice:
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
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>

//Direct implementation
bool is_in(int* begin, int* end, int value)
{
    for( ; begin != end; ++begin) //Loop over range to search in
        if (value == *begin) //If we find value inside range, return true
            return true;
    return false; //If there is no such value return false
}

//Using standard library
bool is_in_stl(int* begin, int* end, int value)
{
    //return if value is found in range
    return std::find(begin, end, value) != end;
}

int main()
{
    int a[] = {1, 6};
    int b[] = {4, 8, 1, 9};
    std::cout << std::boolalpha; //Make output pretty
    //Try if 1 and 6 are in b
    std::cout << is_in(b, b + 4, a[0]) << '\n' << //Warning, make sure that this 4 will be changed if array size changes
                 is_in_stl(std::begin(b), std::end(b), a[1]); //Generic, STL style
}
true
false

http://coliru.stacked-crooked.com/a/75ed28834616079a
Last edited on
Topic archived. No new replies allowed.