Code Yarns ‍👨‍💻

C++ STL: Inserting Vector into Set

(First posted on: 2010-07-16 07:55:40+00:00)

Initializing a set with a vector during its construction is easy:

std::set<int> fooSet(fooVec.begin(), fooVec.end());

Inserting the elements of a vector into an already existing set takes a bit more machinery:

std::copy(fooVec.begin(), fooVec.end(), std::inserter(fooSet, fooSet.end()));

std::copy should be familiar. It inserts the elements of a source container into a destination container. However, it requires the destination container to have enough space for the copied elements. To get around this hassle, the typical solution is to use insert iterators. The commonly used std::back_inserter and std::front_inserter do not work on sets. So, we resort to the std::inserter. But, this requires a position as the second parameter. Thankfully, for associative containers like sets, the second parameter is only a hint, so we can pass any position (like fooSet.end() or fooSet.end()).

Replace vector with any sequence container (list or deque) and set with any associative container (map), and the above operations will work the same on them.