Алгоритм find_if()
Алгоритм 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;
int main()
{
string Pooh_friends[] = { "Пятачок", "Тигра", "Иа-Иа" };
string more_friends[] = { "Квазимодо", "Чип", "Пятачок" };
liststring,allocator lf( more_friends, more_friends+3 );
// заполнить список друзей Пуха
OurFriends::FriendSet( Pooh_friends, 3 );
liststring,allocator::iterator our_mutual_friend;
our_mutual_friend =
find_if( lf.begin(), lf.end(), OurFriends());
// печатается:
// Представьте-ка, наш друг Пятачок - также друг Пуха.
if ( our_mutual_friend != lf.end() )
cout "Представьте-ка, наш друг "
*our_mutual_friend
" также друг Пуха. ";
return 0;
}
Более 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) в случайном порядке. Во втором варианте можно