Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Append

 

Appends two containers using the algorithm std::copy and a std::back_inserter

 

#include <algorithm

//From http://www.richelbilderbeek.nl
template <class Container>
void Append(Container& toWhat, const Container& whatToAppend)
{
  std::copy(whatToAppend.begin(),whatToAppend.end(),std::back_inserter (toWhat));
}

 

 

 

 

 

Append test

 

#include <cassert>
#include <iostream>
#include <algorithm
#include <string>
#include <vector>

//From http://www.richelbilderbeek.nl
template <class Container>
void Append(Container& toWhat, const Container& whatToAppend)
{
  std::copy(whatToAppend.begin(),whatToAppend.end(),std::back_inserter (toWhat));
}

//From http://www.richelbilderbeek.nl/CppCreateVector.htm
template <class T>
const std::vector<T> CreateVector(const T& a, const T& b, const T& c)
{
  std::vector<T> v;
  v.reserve(3);
  v.push_back(a);
  v.push_back(b);
  v.push_back(c);
  return v;
}

//From http://www.richelbilderbeek.nl
int main()
{
  { //Example using std::vector
    std::vector<int> v = CreateVector(1,4,9);
    const std::vector<int> toAppend = CreateVector(16,25,36);
    Append(v,toAppend);
    assert(v[0]==1);
    assert(v[1]==4);
    assert(v[2]==9);
    assert(v[3]==16);
    assert(v[4]==25);
    assert(v[5]==36);
  }
  { //Example using std::string
    std::string s = "Richel";
    const std::string toAppend = " Bilderbeek";
    //(sure, one could also have used 's+=toAppend')
    Append(s,toAppend);
    assert(s=="Richel Bilderbeek");
  }
}


 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict