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

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

Интервал:

Закладка:

Сделать

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

// The printed result might be 7 1 6 3 2 5 4 8,

// or any of 40,319 other possibilities.

Notes

[1] This algorithm is described in section 3.4.2 of Knuth (D. E. Knuth, The Art of Computer Programming. Volume 2: Seminumerical Algorithms , second edition. Addison-Wesley, 1981). Knuth credits Moses and Oakford (1963) and Durstenfeld (1964). Note that there are N! ways of arranging a sequence of N elements. Random_shuffle yields uniformly distributed results; that is, the probability of any particular ordering is 1/N!. The reason this comment is important is that there are a number of algorithms that seem at first sight to implement random shuffling of a sequence, but that do not in fact produce a uniform distribution over the N! possible orderings. That is, it's easy to get random shuffle wrong.

See also

random_sample , random_sample_n , next_permutation , prev_permutation , Random Number Generator

random_sample

Category: algorithms

Component type: function

Prototype

Random_sample is an overloaded name; there are actually two random_sample functions.

template

Random AccessIterator random_sample(InputIterator first, InputIterator last, RandomAccessIterator ofirst, RandomAccessIterator olast)

template

random_sample(InputIterator first, InputIterator last, RandomAccessIterator ofirst, RandomAccessIterator olast, RandomNumberGenerator& rand)

Description

Random_sample randomly copies a sample of the elements from the range [first, last) into the range [ofirst, olast) . Each element in the input range appears at most once in the output range, and samples are chosen with uniform probability. [1] Elements in the output range might appear in any order: relative order within the input range is not guaranteed to be preserved. [2]

Random_sample copies n elements from [first, last) to [ofirst, olast) , where n is min(last – first, olast – ofirst) . The return value is ofirst + n .

The first version uses an internal random number generator, and the second uses a Random Number Generator, a special kind of function object, that is explicitly passed as an argument.

Definition

Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h. This function is an SGI extension; it is not part of the C++ standard.

Requirements on types

For the first version:

• InputIterator is a model of Input Iterator

• RandomAccessIterator is a model of Random Access Iterator

• RandomAccessIterator is mutable.

• InputIterator 's value type is convertible to RandomAccessIterator 's value type.

For the second version:

• InputIterator is a model of Input Iterator

• RandomAccessIterator is a model of Random Access Iterator

• RandomAccessIterator is mutable.

• RandomNumberGenerator is a model of Random Number Generator

• InputIterator 's value type is convertible to RandomAccessIterator 's value type.

• RandomAccessIterator 's distance type is convertible to RandomNumberGenerator 's argument type.

Preconditions

• [first, last) is a valid range.

• [ofirst, olast) is a valid range.

• [first, last) and [ofirst, olast) do not overlap.

• last – first is less than rand 's maximum value.

Complexity

Linear in last – first . At most last – first elements are copied from the input range to the output range.

Example

int main() {

const int N = 10;

const int n = 4;

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

int B[n];

random_sample(A, A+N, B, B+n);

copy(B, B + n, ostream_iterator(cout, " "));

// The printed value might be 1 6 3 5,

// or any of 5039 other possibilities.

}

Notes

[1] This is "Algorithm R" from section 3.4.2 of Knuth (D. E. Knuth, The Art of Computer Programming. Volume 2: Seminumerical Algorithms , second edition. Addison-Wesley, 1981). Knuth credits Alan Waterman. Note that there are N! / n! / (N – n)! ways of selecting a sample of n elements from a range of N elements. Random_sample yields uniformly distributed results; that is, the probability of selecting any particular element is n / N , and the probability of any particular sampling (not considering order of elements) is n! * (N – n)! / N! .

[2] If preservation of the relative ordering within the input range is important for your application, you should use random_sample_n instead. The main restriction of random_sample_n is that the input range must consist of Forward Iterators, rather than Input Iterators.

See also

random_shuffle , random_sample_n , Random Number Generator

random_sample_n

Category: algorithms

Component type: function

Prototype

Random_sample_n is an overloaded name; there are actually two random_sample_n functions.

template

OutputIterator random_sample_n(ForwardIterator first, ForwardIterator last, OutputIterator out, Distance n)

template

OutputIterator random_sample_n(ForwardIterator first, ForwardIterator last, OutputIterator out, Distance n, RandomNumberGenerator& rand)

Description

Random_sample_n randomly copies a sample of the elements from the range [first, last) into the range [out, out + n) . Each element in the input range appears at most once in the output range, and samples are chosen with uniform probability. [1] Elements in the output range appear in the same relative order as their relative order within the input range. [2]

Random_sample copies m elements from [first, last) to [out, out + m) , where m is min(last – first, n) . The return value is out + m .

The first version uses an internal random number generator, and the second uses a Random Number Generator, a special kind of function object, that is explicitly passed as an argument.

Definition

Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h. This function is an SGI extension; it is not part of the C++ standard.

Requirements on types

For the first version:

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

Интервал:

Закладка:

Сделать

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

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


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

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