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

时间:2016-04-25 02:55:34

标签: c++ vector tuples

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

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。如果不是,你怎么能在矢量中找到一个元组。

注意:我包括:iostream,string,tuple,vector和algorithm,并使用命名空间std。

2 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:0)

您可以按如下方式使用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;
}

如果找不到您要查找的元素,它会向找到的序列返回一个迭代器,或者返回结束迭代器。

相关问题