concept iterator in category c++

appears as: iterators, iterator, n iterator, iterators, The iterator
Functional Programming in C++

This is an excerpt from Manning's book Functional Programming in C++.

The STL provides a higher-order function that can sum all the items in a collection: the std::accumulate algorithm. It takes the collection (as a pair of iterators) and the initial value for summing, and it returns the sum of the initial value and all items in the collection. You just need to divide the sum by the total number of scores, as in the previous example. The following implementation doesn’t specify how the summing should be performed—it states only what should be done. The implementation is as general as the problem presentation in figure 2.4.

The algorithm you need is std::find_if. It searches for the first item in the collection that satisfies the specified predicate. In this case, you’re going to search for the first character in the string that isn’t whitespace. The algorithm returns the iterator pointing to the first element in the string that satisfies the predicate. It’s sufficient to remove all elements from the beginning up to that element, thus stripping the whitespace from the start of the string:

std::string trim_left(std::string s)
{
    s.erase(s.begin(),
            std::find_if(s.begin(), s.end(), is_not_space));
    return s;
}

As usual, the algorithm takes a pair of iterators to define the collection. If you pass it the reverse iterators, it’ll search from the end toward the beginning of the string. This way, you can trim the whitespace from the right:

Figure 7.1 The view created by filter stores an iterator to the source collection. The iterator points to only the elements that satisfy the filtering predicate. The user of this view will be able to use it as if it were a normal collection of people with only three elements in it: Martha, Jane, and Rose.

c07_01.png
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest