How to do it...

Use the following iterator adapters to insert new elements in a container:

  • std::back_inserter() to insert elements at the end, for containers that have a push_back() method:
        std::vector<int> v{ 1,2,3,4,5 };
std::fill_n(std::back_inserter(v), 3, 0);
// v={1,2,3,4,5,0,0,0}
  • std::front_inserter() to insert elements at the beginning, for containers that have a push_front() method:
        std::list<int> l{ 1,2,3,4,5 };
std::fill_n(std::front_inserter(l), 3, 0);
// l={0,0,0,1,2,3,4,5}
  • std::inserter() to insert anywhere in a container, for containers that have an insert() method:
        std::vector<int> v{ 1,2,3,4,5 };
std::fill_n(std::inserter(v, v.begin()), 3, 0);
// v={0,0,0,1,2,3,4,5}

std::list<int> l{ 1,2,3,4,5 };
auto it = l.begin();
std::advance(it, 3);
std::fill_n(std::inserter(l, it), 3, 0);
// l={1,2,3,0,0,0,4,5}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset