std::unique and removing duplicates from a container of objects

本文介绍了一种使用C++标准库函数unique结合自定义比较器去除Packet对象重复的方法,通过两种方式实现:一是修改Packet类以支持对象比较;二是提供外部比较函数用于比较指向Packet对象的指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Packet
{
public:
Packet(string fTime, string rID) : filingTime(fTime), recordID(rID)

  string getFilingTime() {return filingTime;}
  string getRecordId() {return recordID;}

private:
  string filingTime;
  string recordID;

};

Two options to be able to use std::unique:

  1. Define an operator== method for Packet and change the vector<Packet*> to vector<Packet>.

    bool Packet::operator==(const Packet& rhs) const
    {
        if (getFilingTime() != rhs.getFilingTime())
            return false;
        if (getSpid() != rhs.getSpid())
            return false;
        return true;
    }
    
    //etc.
    
    int main()
    {
        vector<Packet> pkts;
        pkts.push_back(Packet("10:20", "1004"));
        pkts.push_back(Packet("10:20", "1004")); // not unique (duplicate of the line above)
        pkts.push_back(Packet("10:20", "251"));
        pkts.push_back(Packet("10:20", "1006"));
    
        // remove packet from vector if time and ID are the same
    
         pkts.erase(unique(pkts.begin(), pkts.end()), pkts.end());                   
    
        return 0;
    }
  2. Keep the vector as vector<Packet*> and define a method to compare the elements.

    bool comparePacketPtrs(Packet* lhs, Packet* rhs)
    {
        if (lhs->getFilingTime() != rhs->getFilingTime())
            return false;
        if (lhs->getSpid() != rhs->getSpid())
            return false;
        return true;
    }
    
    //etc.
    
    int main()
    {
        vector<Packet*> pkts;
        pkts.push_back(new Packet("10:20", "1004"));
        pkts.push_back(new Packet("10:20", "1004")); // not unique (duplicate of the line above)
        pkts.push_back(new Packet("10:20", "251"));
        pkts.push_back(new Packet("10:20", "1006"));
    
        // remove packet from vector if time and ID are the same
    
         pkts.erase(unique(pkts.begin(), pkts.end(), comparePacketPtrs), pkts.end());                   
    
        return 0;
    }

 

转载于:https://my.oschina.net/wdyoschina/blog/1502999

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值