zoukankan      html  css  js  c++  java
  • c++:对结构体容器中,重复的元素去重问题

    今天在公司遇到一个问题,需要对容器存储的结构体中的元素进行去重,这里用到了sort与unique,头文件需要加上algorithm

    #include <iostream>
    #include <vector>
    #include<algorithm>
    using namespace std;
    struct stu
    {
      int id;
      bool operator<(const stu &s1)//重载<操作符
      {
        return (*this).id < s1.id;
      }
      bool operator==(const stu &s1)//重载==操作符
      {
        return (*this).id == s1.id;
      }
      bool operator>(const stu &s1)//重载>操作符
      {
        return (*this).id > s1.id;
      }
    };
    struct stuSort
    {
      bool operator()(const stu &s1,const stu &s2)
      {
        return s1.id < s2.id;
      }
    };
    int main()
    {
      vector<struct stu> s;
      struct stu p;
      for(int j = 0; j < 3; j++)
      {
        for(int i = 0; i < 5;i++)
        {
          p.id = i;
          s.push_back(p);
          cout << s[i].id;
        }
      }
      cout << endl;
      struct stuSort sortFunc;
      std::sort(s.begin(),s.end(),sortFunc);
      s.erase(unique(s.begin(),s.end()),s.end());
      for(int i = 0; i<s.size();i++)
        cout << s[i].id << endl;
      return 0;
    }

  • 相关阅读:
    <转> 百度空间 最大子图形问题详解
    Hdu 1124 Factorial
    Uva 457 Linear Cellular Automata
    求01矩阵中的最大的正方形面积
    【HYSBZ】1036 树的统计Count
    【SPOJ】375 Query on a tree
    【POJ】3580 SuperMemo
    【CodeForces】191C Fools and Roads
    【FOJ】2082 过路费
    【HDU】3726 Graph and Queries
  • 原文地址:https://www.cnblogs.com/cansun/p/9340377.html
Copyright © 2011-2022 走看看