Читаем Thinking In C++. Volume 2: Practical Programming полностью

distance(InputIterator first, InputIterator last);

Tells you the number of elements between first and last. More precisely, it returns an integral value that tells you the number of times first must be incremented before it is equal to last. No dereferencing of the iterators occurs during this process.

void advance(InputIterator& i, Distance n);

Moves the iterator i forward by the value of n. (The iterator can also be moved backward for negative values of n if the iterator is also a bidirectional iterator.) This algorithm is aware of bidirectional iterators and will use the most efficient approach.

back_insert_iterator back_inserter(Container& x); front_insert_iterator front_inserter(Container& x); insert_iterator inserter(Container& x, Iterator i);

These functions are used to create iterators for the given containers that will insert elements into the container, rather than overwrite the existing elements in the container using operator= (which is the default behavior). Each type of iterator uses a different operation for insertion: back_insert_iterator uses push_back( ), front_insert_iterator uses push_front( ), and insert_iterator uses insert( ) (and thus it can be used with the associative containers, while the other two can be used with sequence containers). These will be shown in some detail in the next chapter.

const LessThanComparable& min(const LessThanComparable& a, const LessThanComparable& b); const T& min(const T& a, const T& b, BinaryPredicate binary_pred);

Returns the lesser of its two arguments, or returns the first argument if the two are equivalent. The first version performs comparisons using operator<, and the second passes both arguments to binary_pred to perform the comparison.

const LessThanComparable& max(const LessThanComparable& a,   const LessThanComparable& b); const T& max(const T& a, const T& b,   BinaryPredicate binary_pred);

Exactly like min( ), but returns the greater of its two arguments.

void swap(Assignable& a, Assignable& b); void iter_swap(ForwardIterator1 a, ForwardIterator2 b);

Exchanges the values of a and b using assignment. Note that all container classes use specialized versions of swap( ) that are typically more efficient than this general version.

The iter_swap( ) function swaps the values that its two arguments reference.

<p>Creating your own STL-style algorithms</p>

Once you become comfortable with the STL algorithm style, you can begin to create your own generic algorithms. Because these will conform to the conventions of all the other algorithms in the STL, they’re easy to use for programmers who are familiar with the STL, and thus they become a way to "extend the STL vocabulary.".

The easiest way to approach the problem is to go to the header file, find something similar to what you need, and pattern your code after that.[90] (Virtually all STL implementations provide the code for the templates directly in the header files.)

Now that you’re comfortable with the ideas of the various iterator types, the actual implementation is quite straightforward. You can imagine creating an entire additional library of your own useful algorithms that follow the format of the STL.

If you take a close look at the list of algorithms in the standard C++ library, you might notice a glaring omission: there is no copy_if( ) algorithm. Although it’s true that you can accomplish the same thing with remove_copy_if( ), this is not quite as convenient because you have to invert the condition. (Remember, remove_copy_if( ) only copies those elements that don’t match its predicate, in effect removing those that do.) You might be tempted to write a function object adapter that negates its predicate before passing it to remove_copy_if( ), by including a statement something like this:

// Assumes pred is the incoming condition

replace_copy_if(begin, end, not1(pred));

This seems reasonable, but when you remember that you want to be able to use predicates that are pointers to raw functions, you see why this won’t work—not1 expects an adaptable function object. The only solution is to write a copy_if( ) algorithm from scratch. Since you know from inspecting the other copy algorithms that conceptually you need separate iterators for input and output, the following example will do the job.

//: C06:copy_if.h

// Roll your own STL-style algorithm

#ifndef COPY_IF_H

#define COPY_IF_H

Перейти на страницу:

Похожие книги

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

Программирование, программы, базы данных / Программное обеспечение / Книги по IT