I have a C++ STL set.
set<unsigned> baseSet;
I insert a bunch of numbers into it.
for(auto incoming : it->second.in) {
baseSet.insert(incoming);
}
Now I want only the smallest n elements in the set. (I can switch the set's comparator to std::greater if that helps.) Sets don't seem to have a resize function like vectors. How can I shorten it? In-place would be great, and I definately want to take advantage of the fact that sets are sorted instead of doing all the sorting again.
std::setare for specialized uses and you typically do not need and should not use them. You'd probably do better to use avectorandnth_element. - bames53std::unique. See Why you shouldn't use set (and what you should use instead) and Why you should avoid Linked Lists. (The second link refers to linked lists, but the information can also be applied to std::set.) - bames53O(N lg K), whereNis the total number of insertions andKthe number of distinct elements. Throwing everything in a vector which you thensort,uniqueandresizetonhas complexityO(N lg N)but much more favorable constant factors. IfKis not significantly smaller thanN, orNis not "large", using a vector will almost certainly be faster. - Casey