Алгоритм fill_n()
Алгоритм fill_n()
template class ForwardIterator, class Size, class Type
void
fill_n( ForwardIterator first,
Size n, const Type& value );
fill_n() присваивает count элементам из диапазона [first,first+count) значение value.
#include algorithm
#include vector
#include string
#include iostream.h
class print_elements {
public:
void operator()( string elem ) {
cout elem
( _line_cnt++%8 ? " " : " " );
}
static void reset_line_cnt() { _line_cnt = 1; }
private:
static int _line_cnt;
};
int print_elements::_line_cnt = 1;
/* печатается:
исходная последовательность элементов массива:
0 1 1 2 3 5 8
массив после fill_n( ia+2, 3, 9 ):
0 1 9 9 9 5 8
исходная последовательность строк:
Stephen closed his eyes to hear his boots
crush crackling wrack and shells
последовательность после применения fill_n():
Stephen closed his xxxxx xxxxx xxxxx xxxxx xxxxx
xxxxx crackling wrack and shells
*/
int main()
{
int value = 9; int count = 3;
int ia[] = { 0, 1, 1, 2, 3, 5, 8 };
ostream_iterator int iofile( cout, " " );
cout "исходная последовательность элементов массива: ";
copy( ia, ia+7, iofile ); cout " ";
fill_n( ia+2, count, value );
cout "массив после fill_n( ia+2, 3, 9 ): ";
copy( ia, ia+7, iofile ); cout " ";
string replacement( "xxxxx" );
string sa[] = { "Stephen", "closed", "his", "eyes", "to",
"hear", "his", "boots", "crush", "crackling",
"wrack", "and", "shells" };
vector string, allocatorsvec( sa, sa+13 );
cout "исходная последовательность строк: ";
for_each( svec.begin(), svec.end(), print_elements() );
cout " ";
fill_n( svec.begin()+3, count*2, replacement );
print_elements::reset_line_cnt();
cout "последовательность после применения fill_n(): ";
for_each( svec.begin(), svec.end(), print_elements() );
cout " ";
}
Более 800 000 книг и аудиокниг! 📚
Получи 2 месяца Литрес Подписки в подарок и наслаждайся неограниченным чтением
ПОЛУЧИТЬ ПОДАРОКЧитайте также
8.1.1 Алгоритм
8.1.1 Алгоритм Сразу после переключения контекста ядро запускает алгоритм планирования выполнения процессов (Рисунок 8.1), выбирая на выполнение процесс с наивысшим приоритетом среди процессов, находящихся в состояниях "резервирования" и "готовности к выполнению, будучи
Алгоритм iter_swap()
Алгоритм iter_swap() template class ForwardIterator1, class ForwardIterator2 voiditer_swap( ForwardIterator1 a, ForwardIterator2 b );iter_swap() обменивает значения элементов, на которые указывают итераторы a и b.#include algorithm#include list#include iostream.hint main(){int ia[] = { 5, 4, 3, 2, 1, 0 };list int,allocator ilist( ia, ia+6 );typedef list int, allocator ::iterator iterator;iterator iter1 =
Алгоритм lexicographical_compare()
Алгоритм lexicographical_compare() template class InputIterator1, class InputIterator2 boollexicographical_compare(InputIterator1 first1, InputIterator1 last1,InputIterator1 first2, InputIterator2 last2 );template class InputIterator1, class InputIterator2,class Compare boollexicographical_compare(InputIterator1 first1, InputIterator1 last1,InputIterator1 first2, InputIterator2 last2,Compare comp );lexicographical_compare() сравнивает соответственные пары
Алгоритм lower_bound()
Алгоритм lower_bound() template class ForwardIterator, class Type ForwardIteratorlower_bound( ForwardIterator first,ForwardIterator last, const Type &value );template class ForwardIterator, class Type, class Compare ForwardIteratorlower_bound( ForwardIterator first,ForwardIterator last, const Type &value,class Compare );lower_bound() возвращает итератор, указывающий на первую позицию в отсортированной
Алгоритм max()
Алгоритм max() template class Type const Type&max( const Type &aval, const Type &bval );template class Type, class Compare const Type&max( const Type &aval, const Type &bval, Compare comp );max() возвращает наибольшее из двух значений aval и bval. В первом варианте используется оператор "больше", определенный в классе Type; во втором - операция
Алгоритм min()
Алгоритм min() template class Type const Type&min( const Type &aval, const Type &bval );template class Type, class Compare const Type&min( const Type &aval, const Type &bval, Compare comp );min() возвращает меньшее из двух значений aval и bval. В первом варианте используется оператор “меньше”, определенный для типа Type; во втором - операция
Алгоритм merge()
Алгоритм merge() template class InputIterator1, class InputIterator2,class OutputIterator OutputIteratormerge( InputIterator1 first1, InputIterator1 last1,InputIterator2 first2, InputIterator2 last2,OutputIterator result );template class InputIterator1, class InputIterator2,class OutputIterator, class Compare OutputIteratormerge( InputIterator1 first1, InputIterator1 last1,InputIterator2 first2, InputIterator2 last2,OutputIterator result, Compare comp );merge() объединяет
Алгоритм mismatch()
Алгоритм mismatch() template class InputIterator1, class InputIterator2 pairInputIterator1, InputIterator2mismatch( InputIterator1 first,InputIterator1 last, InputIterator2 first2 );template class InputIterator1, class InputIterator2,class BinaryPredicate pairInputIterator1, InputIterator2mismatch( InputIterator1 first, InputIterator1 last,InputIterator2 first2, BinaryPredicate pred );mismatch() сравнивает две последовательности и находит
Алгоритм nth_element()
Алгоритм nth_element() template class RandomAccessIterator voidnth_element( RandomAccessIterator first,RandomAccessIterator nth,RandomAccessIterator last );template class RandomAccessIterator, class Compare voidnth_element( RandomAccessIterator first,RandomAccessIterator nth,RandomAccessIterator last, Compare comp );nth_element() переупорядочивает последовательность, ограниченную диапазоном [first,last), так что все
Алгоритм partial_sort()
Алгоритм partial_sort() template class RandomAccessIterator voidpartial_sort( RandomAccessIterator first,RandomAccessIterator middle,RandomAccessIterator last );templatepartial_sort() сортирует часть последовательности, укладывающуюся в диапазон [first,middle). Элементы в диапазоне [middle,last) остаются неотсортированными. Например, если дан массивint ia[] =
Алгоритм partial_sum()
Алгоритм partial_sum() template class InputIterator, class OutputIterator OutputIteratorpartial_sum(InputIterator first, InputIterator last,OutputIterator result );template class InputIterator, class OutputIterator,class BinaryOperation OutputIteratorpartial_sum(InputIterator first, InputIterator last,OutputIterator result, BinaryOperation op );Первый вариант partial_sum() создает из последовательности, ограниченной
Алгоритм partition()
Алгоритм partition() template class BidirectionalIterator, class UnaryPredicate BidirectionalIteratorpartition(BidirectionalIterator first,BidirectionalIterator last, UnaryPredicate pred );partition() переупорядочивает элементы в диапазоне [first,last). Все элементы, для которых предикат pred равен true, помещаются перед элементами, для которых он равен false.
Алгоритм random_shuffle()
Алгоритм random_shuffle() template class RandomAccessIterator voidrandom_shuffle( RandomAccessIterator first,RandomAccessIterator last );template class RandomAccessIterator,class RandomNumberGenerator voidrandom_shuffle( RandomAccessIterator first,RandomAccessIterator last,RandomNumberGenerator rand);random_shuffle() переставляет элементы из диапазона [first,last) в случайном порядке. Во втором варианте можно