简体   繁体   English

如何在STL容器C ++ 11中查找不同的值

[英]How to find distinct values in an STL container C++11

I might be too tired right now. 我现在可能太累了。 How can you find the distinct values in a container, or range? 如何在容器或范围中找到不同的值?

I've looked through the algorithms library but I can't see anything standard. 我已经浏览了算法库,但是看不到任何标准的库。 I could've sworn there was a standard algorithm to do it. 我可以发誓有一种标准的算法可以做到这一点。

Aside from having a container B which I only add elements from container A which don't already appear... 除了拥有容器B之外,我仅添加容器A中尚未出现的元素...

**EDIT: would be good to get a count of each too.... like... SQL in C++11 **编辑:也将获得每个计数的好处。...就像... C ++ 11中的SQL

Given an input vector v , you can do something like 给定输入向量v ,您可以执行以下操作

std::sort(begin(v), end(v));              // O(N log N) where N = v.size()
auto it = std::unique(begin(v), end(v));  // O(N)

Equivalently (well not really, since you need extra memory, the above method is in-place), you can copy them into and out of a std::set : 同样(由于需要额外的内存,上述方法就位了)(实际上不是,),您可以将它们复制到std::set和从中复制出来:

std::set<T> s(begin(v), end(v));                 // O(N log N);
auto it = std::copy(begin(s), end(s), begin(v)); // O(N);

Note that in both cases you need to actually erase the removed elements 请注意,在两种情况下,您实际上都需要擦除已删除的元素

v.erase(it, end(v)); // O(K), where K is the number of removed duplicates

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM