C ++如何从Class类型的向量中删除重复项? [英] C++ how to remove duplicates from vector of Class type?

查看:50
本文介绍了C ++如何从Class类型的向量中删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,构造函数如下:

I have a class, the constructor looks like this:

myclass(int=0,string="",int=0,string="",int=0,int=0,
        int=0,int=0,string="",int=0,int=0); 

以及带有这种类型元素的向量

and a vector with elements of this type

vector<myclass>myvect;

向量已排序,我正在尝试删除重复项这是行不通的:

the vector is sorted and I am trying to remove duplicates and this is not working:

std::vector<myclass>::iterator it;
   it=std::unique (myvect.begin(), myvect.end());   
   myvect.resize(std::distance(myvect.begin(),it) );

我收到此错误

:algorithm(1862): error C2678: binary '==' :
 no operator found which takes a left-hand operand 
of type 'myclass' (or there is no acceptable conversion) 

知道为什么吗?有什么办法可以从此向量中删除重复项?

any idea why? is there any way I can remove duplicates from this vector?

推荐答案

std :: unique 算法需要知道如何比较两个 myclass 对象是否相等.有两种方法可以执行此操作.首先是实现 myclass :: operator == .第二种是将二进制谓词传递给 std :: unique :

The std::unique algorithm needs to know how to compare two myclass objects for equality. There are two ways you can do this. The first is to implement myclass::operator==. The second is to pass a binary predicate to std::unique:

std::unique (myvect.begin(), myvect.end(),
             [](const myclass& a, const myclass& b) {
               return /* some expression to test equality */;
             }); 

这篇关于C ++如何从Class类型的向量中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆