Search code examples
c++vectorint

C++ How to check if contents of vector exist in another vector?


I'm trying to write a program that checks to see if the contents of one vector exist in another. For example:

vector<int> a = {1, 2};
vector<int> b = {6, 5, 3, 1, 9, 2};

This would return true when comparing these two vectors because the contents of a exist somewhere in b.

vector<int> a = {1, 2}
vector<int> b = {3, 1, 5, 6}

This would return false because not everything in a exists in b.

I've tried it using a while loop, but I got stumped on how to get the loop to break.

bool check_vec(vector<int> a, vector<int> b){

    int checker = 0;

    int i = 0;
    int q = 0;

    while ( true ) {
        if(b.at(i) == a.at(q)) {
            checker++;
            i = 0;
            q++;
            if(checker == a.size())
                return true;

            i++;

        }
    }
}

Solution

  • Use a loop that iterates over the contents of the first vector. You don't need a loop for the second vector, just use std::find.

    for (auto a_elt: a) {
        if (std::find(b.begin(), b.end(), a_elt) == b.end()) {
            return false;
        }
    }
    return true;
    

    You can also use std::all_of:

    return std::all_of(a.begin(), a.end(), [](int a_elt) {
        return std::find(b.begin(), b.end(), a_elt) != b.end();
    });