Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Inserter

 

This page is about two different inserters:

  1. Inserters (general): an output iterator that inserts elements in a container
  2. std::inserter: a type of inserter that inserts at a certain iterator

 

There are three types of inserters:

  1. std::back_inserter
  2. std::front_inserter
  3. std::inserter

 

Inserters can be found in the header file iterator.h.

 

 

 

 

 

Example

 

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

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);
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml