Resources‎ > ‎Programming‎ > ‎C++‎ > ‎C++ Tutorial‎ > ‎

Lesson 11

Practice 1

In the W11 lecture, we have gone through an example of using std::copy template :

#include <list>
#include <iostream>

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

    l.push_back(0);
    l.push_back(0);
    l.push_back(0);
    l.push_back(0);

    std::copy(a, a + 4, l.begin());
    std::list<int>::iterator it;
    for (it = l.begin(); it != l.end(); ++it)
                std::cout << *it << std::endl;
    return 0;
}

In order to use this template, we needed to put "dummy" elements in std::list<int> l;. Your first task is to remove the use of these dummy entries. We would like to apply std::copy to a list, which is empty. (Hint: stdhas several helper functions (know as inserters) to generate iterator adapter [http://www.cplusplus.com/reference/stl/]). You should also replace the for loop with a single line usingstd::copy.

Practice 2

In the above practice, you used one of "iterator adaptor". Your next task is to try all iterator helper functions to identify their different behaviours.

Practice 3

The example in Practice 1 used std::list as a target container. Your next task is to use different containers instd:: and find out which containers will work with the iterator adapter and which ones do not work.

Practice 4

In the W11 lecture, we also looked at using a stream (std::cout) as the target of the std::copy. Your next task is to write a code using std::copy template and a stream iterator to read a series of "space" separated integer numbers and store them in a std::list<int>. Display all the integer numbers read from the standard input and stored in the std::list.


Sample Solutions

Subpages (1): Sample Solutions
Comments