STL/algorithm/for each

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Подсчет суммы с помощью объекта функции

 
#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

Расширение объекта функции, нахождение минимума и максимума

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
 
class CMinMax : public std::unary_function<int, void>
{
protected:
    bool m_bFirst;
public:
    argument_type m_nMin, m_nMax;
public:
    CMinMax(): m_nMin(-1), m_nMax(-1), m_bFirst(true){}
    result_type operator()(argument_type nElem)
    {
        if( m_bFirst) 
            m_nMin = m_nMax = nElem;
        else if (nElem < m_nMin) 
            m_nMin = nElem;
        else if (nElem > m_nMax) 
            m_nMax = nElem;
        m_bFirst = false;
    }
};
 
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, " ") );
    std::cout << std::endl;
 
    CMinMax mm;
    mm = for_each( coll.begin(), coll.end(), mm);
    std::cout << "The max is " << mm.m_nMax << std::endl;
    std::cout << "The min is " << mm.m_nMin << std::endl;
 
    return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The max is 15
The min is 1


Нахождение среднего значения с помощью объекта функции

 
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
 
class CMeanValue : public std::unary_function<int, void>
{
private:
    long m_Num;
    long m_Sum;
public:
    CMeanValue () : m_Num(0), m_Sum(0) {}
    result_type operator()(argument_type elem) { m_Num++; m_Sum += elem; }
    operator double() { return static_cast<double>(m_Sum) / static_cast<double>(m_Num); }
};
 
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, " ") );
    std::cout << std::endl;
 
    double dMv = for_each (coll.begin(), coll.end(), CMeanValue());
    std::cout << "Mean value is: " << dMv << std::endl;
 
    return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Mean value is: 8