Resources‎ > ‎Programming‎ > ‎C++‎ > ‎C++ Tutorial‎ > ‎Lesson 11‎ > ‎

Sample Solutions

Practice 1 - 3

You can use std::back_inserter to insert an element at the back of a container.

#include <list>
#include <iostream>
#include <iterator>

int main() {
    int a[] = {3, 5, 2, 1};
    std::list<int> l;

    std::copy(a, a + 4, back_inserter(l));
    std::copy(l.begin(), l.end(), std::ostream_iterator<int>(std::cout, " "));
    return 0;
}

std::back_inserter is a helper function to create back_inserter_iteratorback_inserter_iterator is often called "iterator adapter", and it adds an element and return newly added element's iterator. Since it usespush_back to add an element, you cannot use it for a container, which does not have push_back.

There are three helper functions

  • front_inserter
  • back_inserter
  • inserter

Practice 4

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

int main() {
    std::list<int> l;

    std::copy(std::istream_iterator<int>(std::cin), 
              std::istream_iterator<int>(),
              std::back_inserter(l));
    std::copy(l.begin(), l.end(), std::ostream_iterator<int>(std::cout, " "));
    return 0;
}

istream_iterator(cin) will return the iterator representing the beginning of cin, while istream_iterator() will return the end. Hence,

std::copy(std::istream_iterator<int>(std::cin),
          std::istream_iterator<int>()

will define [begin, end) of the input stream std::cin

Comments