STL/algorithm/for each
Материал из Wiki.crossplatform.ru
(Различия между версиями)
ViGOur (Обсуждение | вклад)
(Новая страница: «<source lang="cpp"> #include <iostream> #include <vector> #include <algorithm> #include <functional> class CSum : std::unary_function<int, void> { public: ar…»)
Следующая правка →
(Новая страница: «<source lang="cpp"> #include <iostream> #include <vector> #include <algorithm> #include <functional> class CSum : std::unary_function<int, void> { public: ar…»)
Следующая правка →
Версия 11:47, 24 января 2012
#include <iostream> #include <vector> #include <algorithm> #include <functional> class CSum : std::unary_function<int, void> { public: argument_type m_sum; CSum() { m_sum = 0; } result_type operator()(argument_type i) { m_sum += i; } }; int main() { std::vector<int> coll; for( int n = 1; n < 16; ++n) coll.push_back( n); std::copy( coll.begin(), coll.end(), std::ostream_iterator<int>(std::cout, " ") ); CSum s; s = std::for_each( coll.begin(), coll.end(), CSum()); std::cout << "sum of v: " << s.m_sum << std::endl; return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 sum of v: 120