c++ - 使用 std::find 在 std::vector 中查找 std::tuple

标签 c++ vector tuples

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

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   g\n";  // 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 main 如下所示:

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。如果不是,您如何在 vector 中找到元组。

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

最佳答案

您的问题不是在 vector 中搜索元组。您的搜索没问题。

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

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

关于c++ - 使用 std::find 在 std::vector 中查找 std::tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831320/

相关文章:

C++20 格式 sys_time,精度为毫秒

android - 从 pthread 初始化对象时为 "NoSuchMethodError"

c++ - 当 vector 需要更多内存并分配内存时,指针会发生什么变化?

python - Python TypeError:需要一个整数(元组类型元组)-(OpenCV/Numpy)

arrays - 理解 Swift 中元组数组的语法

python - 如何解决在 python 3 中创建 SQL Lite 数据库并打印第一行名称和年龄的十六进制的回溯错误?

c++ - BOOST共享指针导致冗余引用删除

c++ - C - printf 和 scanf - 如何终止输入?

c++ - std::vector 中没有名为 iterator_category 的类型

c++ - 线程完成后从 vector 中移除线程