(C++) Inserter
February 24, 2017 · View on GitHub
(C++) Inserter
This page is about two different inserters:
- Inserters (general): an output iterator that inserts elements in a container
- std::inserter: a type of inserter that inserts at a certain iterator
There are three types of inserters:
Inserters can be found in the header file iterator.h.
Example
Technical facts
Operating system(s) or programming environment(s)
Lubuntu 12.10 (quantal)
Qt Creator 2.5.2
- G++ 4.7.2
Libraries used:
STL: GNU ISO C++ Library, version
4.7.2
Qt project file: CppInserters.pro
TEMPLATE = app CONFIG += console CONFIG -= qt QMAKE_CXXFLAGS += -std=c++11 SOURCES += main.cpp
main.cpp
#include <algorithm> #include <cassert> #include <list> #include <set> #include <vector> int main() { { //std::back_inserter: applies push_back std::vector<int> w { 0,1,2 }; const std::vector<int> to_append { 3,4,5 }; std::copy(to_append.begin(),to_append.end(),std::back_inserter(w)); const std::vector<int> expected { 0,1,2,3,4,5 }; assert(w == expected); } { //std::front_inserter: applies push_front std::list<int> w { 3,4,5 }; const std::list<int> to_prepend { 2,1,0 }; //Must be reversed std::copy(to_prepend.begin(),to_prepend.end(),std::front_inserter(w)); const std::list<int> expected { 0,1,2,3,4,5 }; assert(w == expected); } { //std::inserter: applies insert std::set<int> w { 1,3,5 }; //Don't care about the order const std::set<int> to_insert { 4,0,2 }; //Don't care about the order std::copy(to_insert.begin(),to_insert.end(),std::inserter(w,w.begin())); const std::set<int> expected { 0,1,2,3,4,5 }; assert(w == expected); } }