Finding values in vectors in C++

Viewed 280

It is possible to recreate the following function using only the <algorithm> library without doing any loop for?

bool find(int x, int y, vector<vector<int>> v)
{    
    for(int j=v[0].size()-1;j>=0;j--)
        if((x==v[0][j])and(y==v[1][j])) return true;
    return false;
}

where v={{x values},{y values}} and v[0].size()=v[1].size()

2 Answers

Basically, one way of doing this using find_if:

bool find(int x, int y, std::vector<std::vector<int>> v) {
return v[0].end() != std::find_if(v[0].begin(), v[0].end(),
                                  [x, y, second_vec = v[1].data(), first_data_addr = v[0].data()](int &val) {
                                      return (x == val) && (y == *(second_vec + (&val - first_data_addr)));
                                  });
}

Similarly but without messing up with addresses:

bool find(int x, int y, std::vector<std::vector<int>> v) {
    return v[0].end() != std::find_if(v[0].begin(), v[0].end(),
                                      [x, y, second_vec = v[1].data()](int &val) mutable {
                                          static int j;
                                          auto ans = (x == val) && (y == *(second_vec + j));
                                          j++;
                                          return ans;
                                      });
}

You can use std::mismatch:

bool find(int x, int y, const vector<int>& v1, const vector<int>& v2)
{
   const auto mismatches = [x, y] (int lhs, int rhs) { return lhs != x || rhs != y; };
   return std::mismatch(v1.cbegin(), v1.cend(), v2.cbegin(), mismatches).first != v1.cend();
}
Related