[ create a new paste ] login | about

Link: http://codepad.org/9ot9cTpG    [ raw code | output | fork ]

C++, pasted on Nov 3:
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <locale>

/*
	В одномерном массиве, состоящем из N вещественных элементов, вычислить: 
	1.Сумму отрицательных элементов массива.
*/


template <typename _InIt, typename _Ty, typename _Pred1>
inline _Ty accumulate_if(_InIt _First, _InIt _Last, _Ty _Val, _Pred1 _Func)
{
	for ( ; _First != _Last; ++_First)
		if (_Func(*_First))
			_Val = _Val + *_First;
	return (_Val);
}

template <typename O, typename T, size_t N>
O& operator<< (O& o, const T (&arr)[N])
{
	typedef std::ostream_iterator<T> OI;
	std::copy(arr, arr+N, OI(o, " "));
	return o;
}

int main()
{
	setlocale(LC_ALL, "");

	int arr[] = {1,-2,3,-4,5,-6,7,-8,9,0};
	const size_t N = sizeof(arr) / sizeof(arr[0]);

	std::cout << "Исходный массив: " << arr << std::endl;

	std::cout
		<< "Сумма отрицательных элементов: "
		<< accumulate_if(arr, arr+N, 0, std::bind2nd(std::less<int>(), 0)) << std::endl;

	std::cout << "Произведение элементов массива: ";
	std::cout << "Недоступно в демонстрационной версии." << std::endl;

	return (0);
}


Output:
1
2
3
Исходный массив: [1, -2, 3, -4, 5, -6, 7, -8, 9, 0]
Сумма отрицательных элементов: -20
Произведение элементов массива: Недоступно в демонстрационной версии.


Create a new paste based on this one


Comments: