Find which subvector in a nested vector contains a certain item

Viewed 128

For a nested vector, I want to have a function that returns the index of the subvector that contains a certain item. For example, given this nested vector:

vector<vector<int>> vec {{1, 2, 3},
                         {4, 5, 6},
                         {7, 8, 9, 10}};

I want to have a function that acts like so:

find_subvector(vec, 5); //returns 1 because V[1] contains the element 5.

All of the items among all of the subvectors are unique.

I do have a solution currently, which is to iterate over all of the subvectors and use std::find():

int find_subvector(const vector<vector<int>>& vec, int num) {
    for (int i {}; i < (int)vec.size(); i++)
        if (find(vec[i].begin(), vec[i].end(), num) != vec[i].end())
            return i;
    return -1;
}

But I wanted to know if there was a faster solution, because I will be running this function repeatedly.

0 Answers
Related