Выбрать главу

fill( ++ibegin, --iend, the_lang );

cout "список после fill(++ibegin,--iend):\n";

copy( il.begin(), il.end(), sofile ); cout "\n\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 ? " " : "\n\t" );

}

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 "исходная последовательность элементов массива:\n";

copy( ia, ia+7, iofile ); cout "\n\n";

fill_n( ia+2, count, value );

cout "массив после fill_n( ia+2, 3, 9 ):\n";

copy( ia, ia+7, iofile ); cout "\n\n";

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 "исходная последовательность строк:\n\t";

for_each( svec.begin(), svec.end(), print_elements() );

cout "\n\n";

fill_n( svec.begin()+3, count*2, replacement );

print_elements::reset_line_cnt();

cout "последовательность после применения fill_n():\n\t";

for_each( svec.begin(), svec.end(), print_elements() );

cout "\n";

}

Алгоритм find()

template class InputIterator, class T

InputIterator

find( InputIterator first,

InputIterator last, const T &value );

Элементы из диапазона, ограниченного парой итераторов [first,last), сравниваются со значением value с помощью оператора равенства, определенного для типа элементов контейнера. Как только соответствие найдено, поиск прекращается. find() возвращает итератор типа InputIterator, указывающий на найденный элемент; в противном случае возвращается last.

#include algorithm

#include iostream.h

#include list

#include string

int main()

{

int array[ 17 ] = { 7,3,3,7,6,5,8,7,2,1,3,8,7,3,8,4,3 };

int elem = array[ 9 ];

int *found_it;

found_it = find( &array[0], &array[17], elem );

// печатается: поиск первого вхождения 1 найдено!

cout "поиск первого вхождения "

elem "\t"

( found_it ? "найдено!\n" : "не найдено!\n" );

string beethoven[] = {

"Sonata31", "Sonata32", "Quartet14", "Quartet15",

"Archduke", "Symphony7" };

string s_elem( beethoven[ 1 ] );

list string, allocator slist( beethoven, beethoven+6 );

list string, allocator ::iterator iter;

iter = find( slist.begin(), slist.end(), s_elem );

// печатается: поиск первого вхождения Sonata32 найдено!

cout "поиск первого вхождения "

s_elem "\t"

( found_it ? "найдено!\n" : "не найдено!\n" );

}

Алгоритм find_if()

template class InputIterator, class Predicate

InputIterator

find_if( InputIterator first,

InputIterator last, Predicate pred );

К каждому элементу из диапазона [first,last) последовательно применяется предикат pred. Если он возвращает true, поиск прекращается. find_if() возвращает итератор типа InputIterator, указывающий на найденный элемент; в противном случае возвращается last.

#include algorithm

#include list

#include set

#include string

#include iostream.h

// альтернатива оператору равенства

// возвращает true, если строка содержится в объекте-члене FriendSet

class OurFriends { // наши друзья

public:

bool operator()( const string& str ) {

return ( friendset.count( str ));

}

static void

FriendSet( const string *fs, int count ) {

copy( fs, fs+count,

inserter( friendset, friendset.end() ));

}

private:

static set string, lessstring, allocator friendset;

};

set string, lessstring, allocator OurFriends::friendset;