Item 2. Predicates, Part 1: What remove() Removes

I l @ ve RuBoard

Item 2. Predicates, Part 1: What remove() Removes

Difficulty: 4

This Item lets you test your standard algorithm skills. What does the standard library algorithm remove() actually do, and how would you go about writing a generic function to remove only the third element in a container?

  1. What does the std::remove() algorithm do? Be specific.

  2. Write code that eliminates all values equal to 3 from a std::vector<int> .

  3. A programmer working on your team wrote the following alternative pieces of code to remove the n -th element of a container.

     // Method 1: Write a special-purpose // remove_nth algorithm. // template<typename FwdIter> FwdIter remove_nth( FwdIter first, FwdIter last, size_t n ) {   /* ... */ } // Method 2: Write a function object which returns // true the nth time it's applied, and use // that as a predicate for remove_if. // class FlagNth { public:   FlagNth( size_t n ) : current_(0), n_(n) { }   template<typename T>   bool operator()( const T& ) { return ++current_ == n_; } private:   size_t       current_;   const size_t n_; }; // Example invocation ... remove_if( v.begin(), v.end(), FlagNth(3) ) ... 
    1. Implement the missing part of Method 1.

    2. Which method is better? Why? Discuss anything that might be problematic about either solution.

I l @ ve RuBoard


More Exceptional C++
More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions
ISBN: 020170434X
EAN: 2147483647
Year: 2001
Pages: 118
Authors: Herb Sutter

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net