Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++ STL: Inserting Vector into Set

📅 2010-Jul-16 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, inserters, set, stl, vector ⬩ 📚 Archive

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.

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧