c++ - 在 C++ 中查找 vector 中的值

标签 c++ algorithm c++11 vector find

仅使用 <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/

相关文章:

algorithm - 关于感知器算法伪代码的疑问

algorithm - Myers diff 算法与 Hunt–McIlroy 算法

c++ - 可变参数模板的声明点

c++ - 如何在链表中使用查找

c++ - 为什么该算法适用于反向位

c++ - 'Attempting to upgrade input file specified using deprecated transformation parameters' 是什么意思?

非固定枚举的 C++11 值?

c++ - 使用动态数组的简单地址簿

algorithm - 动态规划 : Timus Online Judge 1172 Ship Routes

c++ - 用 c++0x 和 MingW 编译 CImg