Standard Template Library Programmer's Guide

Здесь есть возможность читать онлайн «Standard Template Library Programmer's Guide» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, Справочники, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Standard Template Library Programmer's Guide: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Standard Template Library Programmer's Guide»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

This document contains reference on SGI STL implementation

Standard Template Library Programmer's Guide — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Standard Template Library Programmer's Guide», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

• There is enough space in the output range to store the copied values. That is, if there are n elements in [first, last) that do not satisfy pred , then [result, result+n) is a valid range.

• result is not an iterator in the range [first, last) .

Complexity

Linear. Exactly last – first applications of pred , and at most last – first assignments.

Example

Fill a vector with the nonnegative elements of another vector.

vector V1;

V.push_back(-2);

V.push_back(0);

V.push_back(-1);

V.push_back(0);

V.push_back(1);

V.push_back(2);

vector V2; remove_copy_if(V1.begin(), V1.end(), back_inserter(V2), bind2nd(less(), 0));

See also

copy , remove , remove_if , remove_copy , unique , unique_copy .

unique

Category: algorithms

Component type: function

Prototype

Unique is an overloaded name; there are actually two unique functions.

template

ForwardIterator unique(ForwardIterator first, ForwardIterator last);

template

ForwardIterator unique(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred);

Description

Every time a consecutive group of duplicate elements appears in the range [first, last) , the algorithm unique removes all but the first element. That is, unique returns an iterator new_last such that the range [first, new_last) contains no two consecutive elements that are duplicates. [1] The iterators in the range [new_last, last) are all still dereferenceable, but the elements that they point to are unspecified. Unique is stable, meaning that the relative order of elements that are not removed is unchanged.

The reason there are two different versions of unique is that there are two different definitions of what it means for a consecutive group of elements to be duplicates. In the first version, the test is simple equality: the elements in a range [f, l) are duplicates if, for every iterator i in the range, either i == f or else *i == *(i-1) . In the second, the test is an arbitrary Binary Predicate binary_pred : the elements in [f, l) are duplicates if, for every iterator i in the range, either i == f or else binary_pred(*i, *(i-1)) is true . [2]

Definition

Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.

Requirements on types

For the first version:

• ForwardIterator is a model of Forward Iterator.

• ForwardIterator is mutable.

• ForwardIterator 's value type is Equality Comparable.

For the second version:

• ForwardIterator is a model of Forward Iterator.

• ForwardIterator is mutable.

• BinaryPredicate is a model of Binary Predicate. [3]

• ForwardIterator 's value type is convertible to BinaryPredicate 's first argument type and to BinaryPredicate 's second argument type.

Preconditions

• [first, last) is a valid range.

Complexity

Linear. Exactly (last – first) – 1 applications of operator== (in the case of the first version of unique ) or of binary_pred (in the case of the second version).

Example

Remove duplicates from consecutive groups of equal int s.

vector V;

V.push_back(1);

V.push_back(3);

V.push_back(3);

V.push_back(3);

V.push_back(2);

V.push_back(2);

V.push_back(1);

vector::iterator new_end = unique(V.begin(), V.end());

copy(V.begin(), new_end, ostream_iterator(cout, " "));

// The output it "1 3 2 1".

Remove all duplicates from a vector of char s, ignoring case. First sort the vector, then remove duplicates from consecutive groups.

inline bool eq_nocase(char c1, char c2) { return tolower(c1) == tolower(c2); }

inline bool lt_nocase(char c1, char c2) { return tolower(c1) < tolower(c2); }

int main() {

const char init[] = "The Standard Template Library";

vector V(init, init + sizeof(init));

sort(V.begin(), V.end(), lt_nocase);

copy(V.begin(), V.end(), ostream_iterator(cout));

cout << endl;

vector::iterator new_end = unique(V.begin(), V.end(), eq_nocase);

copy(V.begin(), new_end, ostream_iterator(cout));

cout << endl;

}

// The output is:

// aaaabddeeehiLlmnprrrStTtTy

// abdehiLmnprSty

Notes

[1] Note that the meaning of "removal" is somewhat subtle. Unique , like remove , does not destroy any iterators and does not change the distance between first and last . (There's no way that it could do anything of the sort.) So, for example, if V is a vector, remove(V.begin(), V.end(), 0) does not change V.size() : V will contain just as many elements as it did before. Unique returns an iterator that points to the end of the resulting range after elements have been removed from it; it follows that the elements after that iterator are of no interest. If you are operating on a Sequence, you may wish to use the Sequence's erase member function to discard those elements entirely.

[2] Strictly speaking, the first version of unique is redundant: you can achieve the same functionality by using an object of class equal_to as the Binary Predicate argument. The first version is provided strictly for the sake of convenience: testing for equality is an important special case.

[3] BinaryPredicate is not required to be an equivalence relation. You should be cautious, though, about using unique with a Binary Predicate that is not an equivalence relation: you could easily get unexpected results.

See also

Binary Predicate , remove , remove_if , unique_copy , adjacent_find

unique_copy

Category: algorithms

Component type: function

Prototype

Unique_copy is an overloaded name; there are actually two unique_copy functions.

template

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Standard Template Library Programmer's Guide»

Представляем Вашему вниманию похожие книги на «Standard Template Library Programmer's Guide» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Standard Template Library Programmer's Guide»

Обсуждение, отзывы о книге «Standard Template Library Programmer's Guide» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.