Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

Counting Iterator

Boost , ,

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Counting Iterator

Author: Дэвид Абрахамс, Джереми Сик, Томас Витт
Contact: ЕслиРазницааргументТогдаРазница_типявляется неопределенным интегральным типом. В противном случаеdifference_typeРазница.

итератор_категорияопределяется по следующему алгоритму:

if (CategoryOrTraversal is not use_default)
    return CategoryOrTraversal
else if (numeric_limits<Incrementable>::is_specialized)
    return iterator-category(
        random_access_traversal_tag, Incrementable, const Incrementable&)
else
    return iterator-category(
         iterator_traversal<Incrementable>::type,
         Incrementable, const Incrementable&)
[Note: implementers are encouraged to provide an implementation of
operator- and a difference_type that avoids overflows in the cases where std::numeric_limits<Incrementable>::is_specialized is true.]

counting_iterator requirements

аргумент должен быть копируемым и уступчивым.

Еслиiterator_categoryконвертируется вforward_iterator_tagилиforward_traversal_tag, то должно быть хорошо сформировано следующее:

Incrementable i, j;
++i;         // pre-increment
i == j;      // operator equal

Еслиiterator_categoryконвертируется вbidirectional_iterator_tagилиbidirectional_traversal_tag, то должно быть также хорошо сформировано следующее выражение:

--i

Еслиiterator_categoryконвертируется вrandom_access_iterator_tagилиrandom_access_traversal_tag, то должно быть также действительным следующее:

counting_iterator::difference_type n;
i += n;
n = i - j;
i < j;

counting_iterator models

Специализацииcounting_iteratorмодели Readable Lvalue Iterator. Кроме того, они моделируют понятия, соответствующие тегам итератора, к которым ихитератор_категорияявляется конвертируемой. Если быCategoryOrTraversalне являетсяuse_default, затемcounting_iteratorмодели концепт, соответствующий тегу итератораКатегорияПутешествия. В противном случае, еслиnumeric_limits::is_specialized, тоcounting_iteratorмодели Random Access Traversal Iterator. В противном случаеcounting_iteratorмоделирует те же концепции обхода итератора, что и.Невероятные.

Counting_iteratorсовместим сCounting_iterator, если и только еслиXсовместим сY.

counting_iterator operations

В дополнение к операциям, требуемым концепциями, моделируемымиCounting_iterator,Counting_iteratorобеспечивает следующие операции.

Counting_iterator();

Requires:Incrementable is Default Constructible.
Effects:Default construct the member m_inc.

counting_iterator (counting_iteratorconst&rhs);

Effects:Construct member m_inc from rhs.m_inc.

явныйсчетчик_iterator(Incrementablex);

Effects:Construct member m_inc from x.

ссылкаоператор*()const;

Returns:m_inc

counting_iterator&operator++();

Effects:++m_inc
Returns:*this

counting_iterator&operator--();

Effects:--m_inc
Returns:*this

Расширяемconst&base()const;

Returns:m_inc
template <class Incrementable>
counting_iterator<Incrementable> make_counting_iterator(Incrementable x);
Returns:An instance of counting_iterator<Incrementable> with current constructed from x.

Example

Этот пример заполняет массив цифрами и второй массив указателями в первый массив, используяcounting_iteratorдля обеих задач. Наконецindirect_iteratorиспользуется для распечатки чисел в первом массиве через опосредование через второй массив.

int N = 7;
std::vector<int> numbers;
typedef std::vector<int>::iterator n_iter;
std::copy(boost::counting_iterator<int>(0),
         boost::counting_iterator<int>(N),
         std::back_inserter(numbers));
std::vector<std::vector<int>::iterator> pointers;
std::copy(boost::make_counting_iterator(numbers.begin()),
          boost::make_counting_iterator(numbers.end()),
          std::back_inserter(pointers));
std::cout << "indirectly printing out the numbers from 0 to "
          << N << std::endl;
std::copy(boost::make_indirect_iterator(pointers.begin()),
          boost::make_indirect_iterator(pointers.end()),
          std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;

Результатом является:

indirectly printing out the numbers from 0 to 7
0 1 2 3 4 5 6

Исходный код для этого примера можно найти здесь.

Статья Counting Iterator раздела может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-07-05 11:01:09/0.0067319869995117/0