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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать
Requirements on types

For the first version, the one that takes two arguments:

• RandomAccessIterator is a model of Random Access Iterator.

• RandomAccessIterator is mutable.

• RandomAccessIterator 's value type is LessThan Comparable.

• The ordering relation on RandomAccessIterator 's value type is a strict weak ordering , as defined in the LessThan Comparable requirements.

For the second version, the one that takes three arguments:

• RandomAccessIterator is a model of Random Access Iterator.

• RandomAccessIterator is mutable.

• StrictWeakOrdering is a model of Strict Weak Ordering.

• RandomAccessIterator 's value type is convertible to StrictWeakOrdering 's argument type.

Preconditions

• [first, last) is a valid range.

Complexity

Stable_sort is an adaptive algorithm: it attempts to allocate a temporary memory buffer, and its run-time complexity depends on how much memory is available. Worst-case behavior (if no auxiliary memory is available) is N (log N)^2 comparisons, where N is last – first , and best case (if a large enough auxiliary memory buffer is available) is N (log N) . [2]

Example

Sort a sequence of characters, ignoring their case. Note that the relative order of characters that differ only by case is preserved.

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

int main() {

char A[] = "fdBeACFDbEac";

const int N = sizeof(A) – 1;

stable_sort(A, A+N, lt_nocase);

printf("%s\n", A);

// The printed result is ""AaBbCcdDeEfF".

}

Notes

[1] Note that two elements may be equivalent without being equal. One standard example is sorting a sequence of names by last name: if two people have the same last name but different first names, then they are equivalent but not equal. This is why stable_sort is sometimes useful: if you are sorting a sequence of records that have several different fields, then you may want to sort it by one field without completely destroying the ordering that you previously obtained from sorting it by a different field. You might, for example, sort by first name and then do a stable sort by last name.

[2] Stable_sort uses the merge sort algorithm; see section 5.2.4 of Knuth. (D. E. Knuth, The Art of Computer Programming. Volume 3: Sorting and Searching . Addison-Wesley, 1975.)

See also

sort , partial_sort , partial_sort_copy , binary_search , lower_bound , upper_bound , less , StrictWeakOrdering, LessThan Comparable

partial_sort

Category: algorithms

Component type: function

Prototype

Partial_sort is an overloaded name; there are actually two partial_sort functions.

template

void partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last);

template

void partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, StrictWeakOrdering comp);

Description

Partial_sort rearranges the elements in the range [first, last) so that they are partially in ascending order. Specifically, it places the smallest middle – first elements, sorted in ascending order, into the range [first, middle) . The remaining last – middle elements are placed, in an unspecified order, into the range [middle, last) . [1] [2]

The two versions of partial_sort differ in how they define whether one element is less than another. The first version compares objects using operator< , and the second compares objects using a function object comp .

The postcondition for the first version of partial_sort is as follows. If i and j are any two valid iterators in the range [first, middle) such that i precedes j , and if k is a valid iterator in the range [middle, last) , then *j < *i and *k < *i will both be false . The corresponding postcondition for the second version of partial_sort is that comp(*j, *i) and comp(*k, *i) are both false. Informally, this postcondition means that the first middle – first elements are in ascending order and that none of the elements in [middle, last) is less than any of the elements in [first, middle) .

Definition

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

Requirements on types

For the first version:

• RandomAccessIterator is a model of Random Access Iterator.

• RandomAccessIterator is mutable.

• RandomAccessIterator 's value type is LessThan Comparable.

• The ordering relation on RandomAccessIterator 's value type is a strict weak ordering , as defined in the LessThan Comparable requirements.

For the second version:

• RandomAccessIterator is a model of Random Access Iterator.

• RandomAccessIterator is mutable.

• StrictWeakOrdering is a model of Strict Weak Ordering.

• RandomAccessIterator 's value type is convertible to StrictWeakOrdering 's argument type.

Preconditions

• [first, middle) is a valid range.

• [middle, last) is a valid range. (It follows from these two conditions that [first, last) is a valid range.)

Complexity

Approximately (last – first) * log(middle – first) comparisons.

Example

int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5};

const int N = sizeof(A) / sizeof(int);

partial_sort(A, A + 5, A + N);

copy(A, A + N, ostream_iterator(cout, " "));

// The printed result is "1 2 3 4 5 11 12 10 9 8 7 6".

Notes

[1] Note that the elements in the range [first, middle) will be the same (ignoring, for the moment, equivalent elements) as if you had sorted the entire range using sort(first, last) . The reason for using partial_sort in preference to sort is simply efficiency: a partial sort, in general, takes less time.

[2] partial_sort(first, last, last) has the effect of sorting the entire range [first, last) , just like sort(first, last) . They use different algorithms, however: sort uses the introsort algorithm (a variant of quicksort), and partial_sort uses heapsort . See section 5.2.3 of Knuth (D. E. Knuth, The Art of Computer Programming. Volume 3: Sorting and Searching . Addison-Wesley, 1975.), and J. W. J. Williams ( CACM 7, 347, 1964). Both heapsort and introsort have complexity of order N log(N) , but introsort is usually faster by a factor of 2 to 5.

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

Интервал:

Закладка:

Сделать

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

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


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

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