使用 std::find 在 std::vector 中查找 std::tuple

use std::find to find a std::tuple in a std::vector

本文关键字:std 查找 tuple find 使用 vector      更新时间:2023-10-16

所以我有一个用以下代码制作的元组坐标向量:

vector<tuple<int, int>> coordinates;
for (int i = 0; i <  7; i++){
   for (int j = 0; j < 6; j++){
      coordinates.push_back(make_tuple(i, j));
   }
}

我正在尝试用以下内容填充"x"、"o"或"."

void displayBoard(vector<tuple<int,int>>& board, vector<tuple<int,int>>& p1, vector<tuple<int,int>>& p2){  // prints out board
  cout << "  a   b   c   d   e   f   gn";  // top row
  for (int i = 1; i < 43; i++){
    if (i % 7 == 0) {
      if (find(p1.begin(), p1.end(), board[i])) cout << "| x |n";
      else if (find(p2.begin(), p2.end(), board[i])) cout << "| o |n";
      else cout << "| . |n";
    } else {
      if (find(p1.begin(), p1.end(), board[i])) cout << "| x ";
      else if (find(p2.begin(), p2.end(), board[i])) cout << "| o ";
      else cout << "| . ";
    }
  }
}

我的 int 主要外观如下:

int main() {
  vector<tuple<int, int>> coordinates;
  for (int i = 0; i <  7; i++){
    for (int j = 0; j < 6; j++){
      coordinates.push_back(make_tuple(i, j));
    }
  }
  vector<tuple<int,int>> p1 = {make_tuple(0,1)};
  vector<tuple<int,int>> p2 = {make_tuple(3,1)};
  displayBoard(coordinates, p1, p2);
  return 0;
}

我使用 (0,1) 和 (3,1) 作为测试坐标,以查看代码是否会运行。长话短说,我想使用 std::find 来查找元组坐标是否被 p1 或 p2 选择,并相应地格式化输出的字符串。因此,如果std::find_if(p1.begin(), p1.end(), make_tuple(2,2))为真,例如用"x"填充单元格。问题是我在编译时收到以下错误:

error: could not convert ‘std::find<__gnu_cxx::__normal_iterator<std::tuple<int, int>*, std::vector<std::tuple<int , int> > >, std::tuple<int, int> >((& p2)->std::vector<_Tp, _Alloc>::begin<std::tuple<int, int>, std::allocator<std::tuple<int, int> > >(), (& p2)->s td::vector<_Tp, _Alloc>::end<std::tuple<int, int>, std::allocator<std::tuple<int, int> > >(), (*(const std::tuple<int, int>*)(& board)->std::vector<_ Tp, _Alloc>::operator[]<std::tuple<int, int>, std::allocator<std::tuple<int, int> > >(((std::vector<std::tuple<int, int> >::size_type)i))))’ from ‘__ gnu_cxx::__normal_iterator<std::tuple<int, int>*, std::vector<std::tuple<int, int> > >’ to ‘bool’

所以问题是我是否可以使用 std::find_if 在 std::vector 中找到一个 std::tuple。如果没有,你怎么能在向量中找到一个元组。

注意:我包括:iostream,字符串,元组,向量和算法,并且正在使用命名空间std。

您的问题不是在向量中搜索元组。您的搜索很好。

您的问题是std::find将迭代器返回到找到的序列成员或结束迭代器值。

代码假定 std::find () 返回已找到该值的bool指示。这不是真的。 std::find()返回一个迭代器。找到的值的迭代器或结束迭代器值。

您可以

按如下方式使用find_if

int main()
{
vector<tuple<int, int>> coordinates;
coordinates.push_back(make_tuple(0,1));
coordinates.push_back(make_tuple(2,3));
auto t = make_tuple(2,3);
auto it = std::find_if(coordinates.begin(), coordinates.end(), [&t](const auto& item) {
    return std::get<0>(t) == std::get<0>(item)
           && std::get<1>(t) == std::get<1>(item);
    });
    if(it!=coordinates.end())
      cout << "found" << endl;
}
它将迭代器返回到找到的

序列,如果尚未找到您要查找的元素,则返回结束迭代器。