Алгоритм inner_product()
Алгоритм inner_product()
template class InputIterator1, class InputIterator2
class Type
Type
inner_product(
InputIterator1 first1, InputIterator1 last,
InputIterator2 first2, Type init );
template class InputIterator1, class InputIterator2
class Type,
class BinaryOperation1, class BinaryOperation2
Type
inner_product(
InputIterator1 first1, InputIterator1 last,
InputIterator2 first2, Type init,
BinaryOperation1 op1, BinaryOperation2 op2 );
Первый вариант суммирует произведения соответственных членов обеих последовательностей и прибавляет результат к начальному значению init. Первая последовательность ограничена итераторами [first1,last1), вторая начинается с first2 и обходится синхронно с первой. Например, если даны последовательности {2,3,5,8} и {1,2,3,4}, то результат вычисляется следующим образом:
2*1 + 3*2 + 5*3 + 8*4
Если начальное значение равно 0, алгоритм вернет 55.
Во втором варианте вместо сложения используется бинарная операция op1, а вместо умножения - бинарная операция op1. Например, если для приведенных выше последовательностей применить вычитание в качестве op1 и сложение в качестве op2, то результат будет вычисляться так:
(2+1) - (3+2) - (5+3) - (8+4)
inner_product() - это один из численных алгоритмов. Для его использования в программу необходимо включить заголовочный файл .
#include numeric
#include vector
#include iostream.h
int main()
{
int ia[] = { 2, 3, 5, 8 };
int ia2[] = { 1, 2, 3, 4 };
// перемножить пары элементов из обоих массивов,
// сложить и добавить начальное значение: 0
int res = inner_product( &ia[0], &ia[4], &ia2[0], 0 );
// печатает: скалярное произведение массивов: 55
cout "скалярное произведение массивов: "
res endl;
vectorint, allocator vec( ia, ia+4 );
vectorint, allocator vec2( ia2, ia2+4 );
// сложить пары элементов из обоих векторов,
// вычесть из начального значения: 0
res = inner_product( vec.begin(), vec.end(),
vec2.begin(), 0,
minusint(), plusint() );
// печатает: скалярное произведение векторов: -28
cout "скалярное произведение векторов: "
res endl;
return 0;
}
Более 800 000 книг и аудиокниг! 📚
Получи 2 месяца Литрес Подписки в подарок и наслаждайся неограниченным чтением
ПОЛУЧИТЬ ПОДАРОКЧитайте также
8.1.1 Алгоритм
8.1.1 Алгоритм Сразу после переключения контекста ядро запускает алгоритм планирования выполнения процессов (Рисунок 8.1), выбирая на выполнение процесс с наивысшим приоритетом среди процессов, находящихся в состояниях "резервирования" и "готовности к выполнению, будучи
Алгоритм inplace_merge()
Алгоритм inplace_merge() template class BidirectionalIterator voidinplace_merge( BidirectionalIterator first,BidirectionalIterator middle,BidirectionalIterator last );template class BidirectionalIterator, class Compare voidinplace_merge( BidirectionalIterator first,BidirectionalIterator middle,BidirectionalIterator last, Compare comp );inplace_merge() объединяет две соседние отсортированные последовательности,
Алгоритм 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) в случайном порядке. Во втором варианте можно