如何删除排序向量中的重复项 [英] How to remove duplicated items in a sorted vector

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

问题描述

我目前有一个 vectorc 包含 {1,2,2,4,5,5,6}我想删除重复的数字,以便 c 将有{1,4,6}.互联网上的许多解决方案似乎只是删除了其中一个重复项,但我正在尝试删除所有出现的重复号码.

I currently have a vector<int> c which contains {1,2,2,4,5,5,6} and I want to remove the duplicated numbers so that c will have {1,4,6}. A lot of solutions on the internet seem to just remove one of the duplicates, but I'm trying to remove all occurrences of the duplicated number.

假设 c 总是排序的.

我现在有

#include <iostream>
#include <vector>

int main() {
  vector<int> c{1,2,2,4,5,5,6};
  for (int i = 0; i < c.size()-1; i++) {
    for (int j=1; j<c.size();j++){
      if(c[i] == c[j]){
         // delete i and j? 
      }
    }
  }
}

我尝试使用两个 for 循环,以便可以比较当前元素和下一个元素.这就是我怀疑的地方.我不确定我是否正确地解决了这个问题.

I tried to use two for-loops so that I can compare the current element and the next element. This is where my doubt kicked in. I'm not sure if I'm approaching the problem correctly.

我能否获得有关如何解决问题的帮助?

Could I get help on how to approach my problem?

推荐答案

这段代码基于这样的认识,即一个元素在排序列表中是唯一的,当且仅当它与紧邻它的两个元素都不同(除了开始和结束元素,每个元素都与一个元素相邻).这是真的,因为所有相同的元素必须在排序数组中相邻.

This code is based on the insight that an element is unique in a sorted list if and only if it is different from both elements immediately adjacent to it (except for the starting and ending elements, which are adjacent to one element each). This is true because all identical elements must be adjacent in a sorted array.

void keep_unique(vector <int> &v){
    if(v.size() < 2){return;}

    vector <int> unique;

    // check the first element individually
    if(v[0] != v[1]){
        unique.push_back(v[0]);
    }

    for(unsigned int i = 1; i < v.size()-1; ++i){
        if(v[i] != v[i-1] && v[i] != v[i+1]){
            unique.push_back(v[i]);
        }
    }

    // check the last item individually
    if(v[v.size()-1] != v[v.size()-2]){
        unique.push_back(v[v.size()-1]);
    }

    v = unique;
}

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

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