仅使用 <algorithm>
即可重新创建以下函数库不做任何循环?
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;
}
哪里v={{x values},{y values}}
和v[0].size()=v[1].size()
最佳答案
基本上,使用 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)));
});
}
类似,但不会弄乱地址:
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;
});
}
关于c++ - 在 C++ 中查找 vector 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359516/