Читаем 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

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

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