且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从c ++中的列表中删除重复的值?

更新时间:2023-02-13 22:09:54

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

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;
    }
  }
}