如何从c ++中的列表中删除重复的值? [英] How can I remove duplicate values from a list in c++?

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

问题描述

我是新的c ++和坚持一个问题。我使用列表来存储字符串值。
现在我想从该字符串中删除重复的值。任何人都可以告诉我如何做。

I am new to c++ and stuck to a problem. I am using list for storing string values. now i want to remove the duplicate values from that string. Can anyone tell me how do this.

任何示例代码都将非常感激。

Any sample code will be highly appreciate.

推荐答案

如果列表已排序,请使用其唯一方法。

If the list is sorted, use its unique method.

如果列表未排序(且不想排序) :

If the list isn't sorted (and you don't want to sort it):

set<string> found;
for (list<string>::iterator x = the_list.begin(); x != the_list.end();) {
  if (!found.insert(*x).second) {
    x = the_list.erase(x);
  }
  else {
    ++x;
  }
}

为避免将字符串复制到集合中: p>

To avoid copying the strings into the set:

struct less {
  template<class T>
  bool operator()(T &a, T &b) {
    return std::less<T>()(a, b);
  }
};
struct deref_less {
  template<class T>
  bool operator()(T a, T b) {
    return less()(*a, *b);
  }
};

void remove_unsorted_dupes(list<string> &the_list) {
  set<list<string>::iterator, deref_less> found;
  for (list<string>::iterator x = the_list.begin(); x != the_list.end();) {
    if (!found.insert(x).second) {
      x = the_list.erase(x);
    }
    else {
      ++x;
    }
  }
}

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

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