Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Replace_range

 

Replace code snippet that replaces a range by another range.

 

#include <cassert>
#include <vector>

const std::vector<int> Replace_range(
  const std::vector<int>& v,
  const std::vector<int>& oldvalue,
  const std::vector<int>& newvalue)
{
  assert(v.size() >= oldvalue.size() && "oldvalue must have less elements than v");

  std::vector<int> w;

  std::vector<int>::const_iterator from = v.begin();
  std::vector<int>::const_iterator to = from + oldvalue.size();
  const std::vector<int>::const_iterator end = v.end();

  assert(to < v.end());

  for (; to != end; ++from, ++to)
  {
    if (std::equal(from,to,oldvalue.begin()))
    {
      std::copy(newvalue.begin(),newvalue.end(),std::back_inserter(w));
      from += oldvalue.size();
      to += oldvalue.size();
    }
    else
    {
      w.push_back(*from);
    }

  }
  std::copy(from,end,std::back_inserter(w));

  return w;
}

 

 

 

 

 

Replace_range test

 

#include <algorithm
#include <iostream>
#include <iterator>

int main()
{
  std::vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  v.push_back(5);
  v.push_back(6);
  v.push_back(7);
  v.push_back(8);
  v.push_back(9);

  std::vector<int> from;
  from.push_back(2);
  from.push_back(3);
  from.push_back(4);

  std::vector<int> to;
  to.push_back(1);
  to.push_back(2);
  to.push_back(3);
  to.push_back(4);
  to.push_back(5);

  //Write v to screen
  //From http://www.richelbilderbeek.nl/CppCoutContainer.htm
  std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout," "));
  std::cout << std::endl;

  for (int i = 0; i!=10; ++i)
  {
    v = Replace_range(v,from,to);

    //Write v to screen
    //From http://www.richelbilderbeek.nl/CppCoutContainer.htm
    std::copy(v.begin(),v.end(),
      std::ostream_iterator<int>(std::cout," "));
    std::cout << std::endl;
  }
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict