std::vector 去重

一 方案

std::vector 去重分为3步:

  1. 使用std::sort排序;
  2. 使用std::unique移除相邻重复元素;
  3. 使用vector::erase擦除vector新逻辑结尾至vector结尾的元素。

二 例子

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

// 打印vector元素
void print(const std::string& text, const std::vector<int>& vc) {
  std::cout << text << std::endl;
  auto it = vc.begin();
  while (it != vc.end())
  {
    std::cout << *it << " ";
    ++it;
  }
  std::cout << std::endl;
}

int main() {

  std::vector<int> vc = { 9, 7,6 ,9, 8, 2, 5, 6, 2,1 };
  print("origin vc:", vc);
  std::sort(vc.begin(), vc.end());
  print("after sort vc:", vc);
  auto index_it = std::unique(vc.begin(), vc.end());
  print("after sort + unique vc:", vc);
  vc.erase(index_it, vc.end());
  print("after sort + unique + erase vc:", vc);
  std::cin.get();
  return 0;
}

结果:

三 注意

  1. std::sort默认是升序排列,采用operator< 比较元素。
  2. std::unique只能移除相邻的相等元素,所以要先将元素排序。std::unique通过用覆写要被擦除的元素的方式迁移范围中的元素进行移除。保持剩余元素的相对顺序,且不更改容器的物理大小。std::unique返回值是指向范围新结尾的向前迭代器。
  3. 容器vector的erase既可以擦除单个元素,也可以擦除一个范围的元素。erase会重新调整容器物理大小。
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值