C++ C++;无法对自定义对象的向量进行排序
编辑,更新:非常好的答案,谢谢大家。我已经为<和==运算符编写了运算符重载。我不再收到错误。我还通过引用而不是通过值将向量正确地传递到我的C++ C++;无法对自定义对象的向量进行排序,c++,sorting,object,vector,duplicates,C++,Sorting,Object,Vector,Duplicates,编辑,更新:非常好的答案,谢谢大家。我已经为顶点自己,编译器必须被告知如何考虑两个VTETECE相等。定义算术运算符的最简单方法如下: struct Vertex { string name; int num; public: Vertex(); Vertex(string, int); void printVertex(); friend bool operator==(Vertex const& lhs, Vertex const&a
removeDup(vector&)中代码>函数
我有一个需要从中删除重复项的对象向量,但我收到了一个我不熟悉的错误(错误如下)。它是一个非常简单的对象,公开包含在名为Graph
的类中:
struct Vertex
{
string name;
int num;
public:
Vertex();
Vertex(string, int);
void printVertex();
};
我已经通读了一些关于这个()
但是当我尝试使用unique对向量进行排序时,我得到了一个非常奇怪的错误
我使用push_back
添加到向量:
vector<Graph::Vertex> v;
Graph::Vertex first(string1, count);
v.push_back(first);
我对C++编程有点陌生,不知道为什么会发生这种错误,或者它意味着什么。有人能解释一下我为什么会犯这个错误吗?我需要写一个操作符重载函数来处理它吗
为了解决这个错误,我非常努力地在谷歌上搜索(并使用这个网站),但最后不得不在这里发表我的第一篇文章寻求帮助。提醒:这是一个家庭作业,所以我决定不包括我的代码的其余部分,以避免被填鸭式的回答,但如果我没有提供足够的信息,请告诉我。
- 当需要排序时,编译器不知道哪个顶点放在另一个顶点之前。你需要告诉编译器这个信息。因此,使用3参数
std::sort()
函数,或者编写一个重载的操作符两个识别唯一对象,您需要能够测试相等性(毕竟,您还需要如何识别相同的对象)
假设有两个对象a
和b
。检验平等性的标准方法是a==b
。如果对int
s进行操作,编译器知道如何处理此表达式(例如,发出CMP
指令)
但是,由于您定义了代码>顶点自己,编译器必须被告知如何考虑两个VTETECE相等。定义算术运算符的最简单方法如下:
struct Vertex
{
string name;
int num;
public:
Vertex();
Vertex(string, int);
void printVertex();
friend bool operator==(Vertex const& lhs, Vertex const& rhs)
{ return lhs.num == rhs.num; } // or whatever you wish to do here
};
请注意:在定义==
时,您可能还希望定义=代码>保持一致。您还可能希望定义所有的=
,以便可以进行比较…std::sort
和std::unique
都需要比较项目来完成它们的工作。不过,它们有一些不同的要求:std::unique
比较是否相等,以及std::sort
比较是否排序。对于您的案例,一个明显的可能性是此一般订单上的代码:
bool operator==(Vertex const &other) const {
return num == other.num;
}
bool operator<(Vertex const &other) const {
return num < other.num;
}
这会将比较代码放在排序旁边,因此很容易看到您是如何进行排序的。您可以使用单独的函数或函数对象,但这样做意味着您需要小心使用名称,以确保其描述排序顺序:
struct by_name {
bool operator()(Vertex const &a, Vertex const &b) const {
return a.name < b.name;
}
};
// ...
std:sort(v.begin(), v.end(), by_name());
struct by_name{
布尔运算符()(顶点常数&a、顶点常数&b)常数{
返回a.name
编译器在尝试排序时不知道如何将一个顶点对象与另一个顶点对象进行比较。可以通过在顶点类中重载<操作符来实现。此操作符将用于比较两个顶点,并将一个放置在另一个顶点之前。您需要重载运算符==以在unique中使用,因为它将使用运算符==检查一个顶点是否等于另一个顶点,从而找到重复的顶点。精彩的解释!非常感谢
bool operator==(Vertex const &other) const {
return num == other.num;
}
bool operator<(Vertex const &other) const {
return num < other.num;
}
std::sort(v.begin(), v.end(),
[](Vertex const &a, Vertex const &b) { return a.name < b.name; });
struct by_name {
bool operator()(Vertex const &a, Vertex const &b) const {
return a.name < b.name;
}
};
// ...
std:sort(v.begin(), v.end(), by_name());