Check if an array elements exist in the another array c++

Hi ROOTers,
I have two arrays like this: A={ 1, 3, 7} B={ 4, 5, 2, 3, 8,7,1}
In C++, I want to check whether all elements of the array A exist in the array B or not?
Could you please help me to do this?
Thanks in advance

This does not seem a ROOT related issue but more a C/C++ question.
A good start, for ordered collection can be std::includes: en.cppreference.com/w/cpp/algorithm/includes

I compile the following code in the Coliru ( coliru.stacked-crooked.com) in the internet without any errors.

[code]#include
#include
#include

using namespace std;

bool InArray (int Haystack[], size_t size, int needle);

int main ()
{
int A[] = { 1, 3 };
int B[] = { 4, 5, 2, 3, 8, 7, 1 };

//const int kNumElemsInArrayA = sizeof (A) / sizeof (A[0]);
const int kNumElemsInArrayB = sizeof (B) / sizeof (B[0]);

for (int i : A)
{
if (!InArray (B, kNumElemsInArrayB, i))
{
cout << “Not all elements are in array B”;
system (“pause”);
return 0;
}
}
cout << “All elements are in array B”<< endl;
return 0;
}

bool InArray (int Haystack[], size_t size, int needle)
{
for (size_t i = 0; i < size; i++)
{
if (Haystack[i] == needle)
return true;
}

return false;
}[/code]
but compiling in ROOT I encountered with the following error.

Error: Invalid type ';return0;}}cout<<"All' in declaration of 'elements are in array B"<<endl' main.cxx:26: Error: Symbol ;return0;}}cout<<"All elements are in array B"<<endl is not defined in current scope main.cxx:26: Error: improper lvalue main.cxx:26: *** Interpreter error recovered ***
can you help me?

Hi,

how exactly did you run this on what root version?
You should try to save the code in a file called main.C and to type root main.C in the shell.

Hi,
I run the code by typing “.X main.C” in the root, Version 5.34/28.

You have no support for C+±11 with ROOT5 (cint), so that

for (int i : A)
is not understood properly. You should rewrite it as for(int j=0;j<2;++j) int i = A[j];

Or install ROOT6 (cling), that supports this type of syntax.

Or compile with aclic (.X script.C+, and flag -std=c+±11 is on)

Hi,

since we are talking about c++11, I’d like to come back to the initial suggestion and propose a more generic and smaller version of the code*. ROOT6 is of course able to digest it.

Cheers,
Danilo

#include <algorithm>
#include <vector>
#include <iostream>

int myMacro ()
{
  std::vector<int> A { 1, 3, 123 };
  std::vector<int> B { 4, 5, 2, 3, 8, 7, 1 };

  std::sort(std::begin(A), std::end(A));
  std::sort(std::begin(B), std::end(B));

  auto includes = std::includes(std::begin(B), std::end(B),
                                std::begin(A), std::end(A));

  std::cout << "All elements are " << (includes? "": "not ") << "in array B"<< std::endl;

  return 0;
}