[英]c++ find var in vector of structs
I'm trying to make a c++ program where I can dynamically add points to a list, and then search for if those points are in the list.我正在尝试制作一个 C++ 程序,我可以在其中动态地将点添加到列表中,然后搜索这些点是否在列表中。
I was trying originally to use sets, but am now trying to use vectors.我最初尝试使用集合,但现在尝试使用向量。 My code below will run, but gets an error involving the search if statement.
我下面的代码将运行,但会出现涉及搜索 if 语句的错误。
#include <stdio.h> /* printf */
#include <bits/stdc++.h> /* vector of strings */
#include <algorithm>
#include <vector>
using namespace std;
void solve_point(vector<vector<char>> &board)
{
printf("solve_point\n");
board[2][2] = 'c';
}
struct point
{
int x;
int y;
};
int main()
{
vector<point> vec;
point point1{4, 1};
point point1{8, 3};
vec.push_back(point1);
if (find(vec.begin(), vec.end(), point1) != vec.end())
{
printf("point1 found in vec\n");
}
else
{
printf("point1 not found in vec\n");
}
}
This leads to some errors saying:这会导致一些错误说:
/usr/include/c++/7/bits/predefined_ops.h:241:17: error: no match for ‘operator==’ (operand types are ‘point’ and ‘const point’)
{ return *__it == _M_value; }
..and..
/usr/include/c++/7/bits/predefined_ops.h:241:17: note: ‘point’ is not derived from ‘const __gnu_cxx::new_allocator<_Tp>’
{ return *__it == _M_value; }
I encountered an error similar to this earlier when I was trying to insert a point into a set, is there something wrong with my struct point initialization?我之前在尝试将一个点插入一个集合时遇到了与此类似的错误,我的结构点初始化有问题吗? Thanks
谢谢
You are experiencing two problems:您遇到两个问题:
std::find()
needs a way of comparing two struct point
instances. std::find()
需要一种比较两个struct point
实例的方法。 For this, it defaults to using point::operator==()
which is not defined.point::operator==()
。 You have to add this manually:struct point
{
int x;
int y;
bool operator==(const point& rhs) const {
return x == rhs.x and y == rhs.y;
}
};
Alternatively you can use std::find_if()
which allows you to supply a lambda.或者,您可以使用
std::find_if()
来提供一个 lambda。 However, instances of a class like point
will most likely need to be compared in a lot of places so defining operator==()
is definitely a good idea.然而,像
point
这样的类的实例很可能需要在很多地方进行比较,因此定义operator==()
绝对是一个好主意。
point1
.point1
。 Rename it to for example point2
.point2
。 Working example:工作示例:
#include <bits/stdc++.h> /* vector of strings */
#include <algorithm>
#include <vector>
using namespace std;
void solve_point(vector<vector<char>> &board)
{
printf("solve_point\n");
board[2][2] = 'c';
}
struct point
{
int x;
int y;
bool operator==(const point& rhs) const {
return x == rhs.x and y == rhs.y;
}
};
int main()
{
vector<point> vec;
point point1{4, 1};
point point2{8, 3};
vec.push_back(point1);
if (find(vec.begin(), vec.end(), point1) != vec.end())
{
printf("point1 found in vec\n");
}
else
{
printf("point1 not found in vec\n");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.