Standard Template Library Programmer's Guide
Здесь есть возможность читать онлайн «Standard Template Library Programmer's Guide» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, Справочники, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Standard Template Library Programmer's Guide
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
(Earlier versions of the STL used get_temporary_buffer and return_temporary_buffer instead of temporary_buffer . temporary_buffer is more convenient, because it does not require using uninitialized_copy , and in some cases it is also more efficient. Additionally, it is much easier to write exception-safe code with temporary_buffer than with get_temporary_buffer and return_temporary_buffer .)
int main() {
vector V(50);
iota(V.begin(), V.end(), 1);
temporary_buffer::iterator, int> buf(V.begin(), V.end());
copy(V.rbegin(), V.rbegin() + buf.size(), buf.begin());
copy(buf.begin(), buf.end(), ostream_iterator(cout, "\n"));
}
Defined in the standard header memory, and in the nonstandard backward-compatibility header algo.h. This class is an SGI extension; it is not part of the C++ standard.
Parameter | Description | Default |
---|---|---|
ForwardIterator |
The type of the iterators passed as arguments to temporary_buffer 's constructor. | |
T |
The type of object stored in the temporary buffer. | iterator_traits::value_type [2] |
None. temporary_buffer is vaguely similar to a Container, but it does not provide the entire Container interface. In particular, it is not a model of DefaultConstructible or Assignable.
• ForwardIterator is a model of Forward Iterator
• ForwardIterator is mutable.
• T has a constructor that can take a single argument of ForwardIterator 's value type.
None.
Member | Description |
---|---|
temporary_buffer(ForwardIterator first, ForwardIterator last) |
Allocates a temporary buffer that holds at most last – first elements of type T , and constructs those elements. The initial values of the elements are unspecified. Precondition: [first, last) is a valid range. |
~temporary_buffer() |
Destroys the elements in the temporary buffer, and deallocates the buffer itself. |
T* begin() |
Returns a pointer to the first element in the buffer. |
T* end() |
Returns a pointer that points one past the last element in the buffer. |
ptrdiff_t requested_size() const |
Returns the value last – first , where first and last are the arguments that were passed to the constructor. |
ptrdiff_t size() const |
Returns the number of elements in the temporary buffer, end() – begin() . The return value satisfies the constraint 0 <= size() <= requested_size() . |
[1] The requested size is last – first . The size of the temporary buffer is never larger than the requested size, but it might well be smaller; the size might even be zero. The intention is that temporary_buffer will allocate as large a buffer as is possible without hurting performance. Note that determining this maximum size is quite difficult: it depends on cache size, physical versus virtual memory, heap fragmentation, and so on. A good implementation of temporary_buffer must be nonportable.
[2] The iterator_traits mechanism relies on partial specialization of templates. If your compiler does not yet implement this features, then you will not be able to use this default parameter; you will have to provide both template arguments.
get_temporary_buffer
Category: allocators
Component type: function
template
pair get_temporary_buffer(ptrdiff_t len, T*);
Some algorithms, such as stable_sort and inplace_merge , are adaptive : they attempt to use extra temporary memory to store intermediate results, and their run-time complexity is better if that extra memory is available.
The first argument to get_temporary_buffer specifies the requested size of the temporary buffer, and the second specifies the type of object that will be stored in the buffer. That is, get_temporary_buffer(len, (T*) 0) requests a buffer that is aligned for objects of type T and that is large enough to hold len objects of type T . [1]
The return value of get_temporary_buffer is a pair P whose first component is a pointer to the temporary buffer and whose second argument indicates how large the buffer is: the buffer pointed to by P.first is large enough to hold P.second objects of type T . P.second is greater than or equal to 0 [2], and less than or equal to len [1]. Note that P.first is a pointer to uninitialized memory, rather than to actual objects of type T ; this memory can be initialized using uninitialized_copy , uninitialized_fill , or uninitialized_fill_n .
As the name suggests, get_temporary_buffer should only be used to obtain temporary memory. If a function allocates memory using get_temporary_buffer , then it must deallocate that memory, using return_temporary_buffer [3], before it returns.
Note: get_temporary_buffer and return_temporary_buffer are only provided for backward compatibility. If you are writing new code, you should instead use the temporary_buffer class.
Defined in the standard header memory, and in the nonstandard backward-compatibility header algo.h.
• len is greater than 0 .
int main() {
pair P = get_temporary_buffer(10000, (int*) 0);
int* buf = P.first;
ptrdiff_t N = P.second;
uninitialized_fill_n(buf, N, 42);
int* result = find_if(buf, buf + N, bind2nd(not_equal_to(), 42));
assert(result == buf + N);
return_temporary_buffer(buf);
}
[1] The argument len is a request, rather than a requirement. The intention is that get_temporary_buffer will return as large a buffer as can be allocated without hurting performance. Note that determining this maximum size is quite difficult: it depends on cache size, physical versus virtual memory, heap fragmentation, and so on. A good implementation of get_temporary_buffer must be nonportable.
[2] If P.second is 0, this means that get_temporary_buffer was unable to allocate a temporary buffer at all. In that case, P.first is a null pointer.
[3] It is unspecified whether get_temporary_buffer is implemented using malloc , or ::operator new , or some other method. The only portable way to return memory that was allocated using get_temporary_buffer is to use return_temporary_buffer .
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Standard Template Library Programmer's Guide»
Представляем Вашему вниманию похожие книги на «Standard Template Library Programmer's Guide» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Standard Template Library Programmer's Guide» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.