STL/algorithm/for each

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

(Различия между версиями)
Перейти к: навигация, поиск
 
Строка 1: Строка 1:
 +
== Печать с помощью std::for_each  ==
 +
<source lang="cpp"> 
 +
#include <iostream>
 +
#include <algorithm>
 +
 +
void print( int n)
 +
{
 +
    std::cout << n;
 +
}
 +
 +
int main()
 +
 +
    int coll[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 +
    std::for_each( coll, coll + sizeof(coll)/sizeof(*coll), print);
 +
 +
    return 0;
 +
}
 +
</source> 
 +
 +
<source lang="bash">0123456789</source>
 +
== Подсчет суммы с помощью объекта функции ==  
== Подсчет суммы с помощью объекта функции ==  
<source lang="cpp">   
<source lang="cpp">   

Текущая версия на 12:49, 24 января 2012

Содержание

[править] Печать с помощью std::for_each

 
#include <iostream>
#include <algorithm>
 
void print( int n)
{
    std::cout << n;
}
 
int main()
{   
    int coll[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    std::for_each( coll, coll + sizeof(coll)/sizeof(*coll), print);
 
    return 0;
}
0123456789

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

 
#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

[править] Добавление числа к каждому элементу коллекции с помощью объекта функции

 
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
 
class CEditValue : public std::unary_function<int, void>
{
private:
    argument_type m_Value;
public:
    CEditValue(argument_type v) : m_Value(v) {}
    result_type operator()( argument_type &rElem) const { rElem += m_Value; }
};
 
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;
 
    for_each (coll.begin(), coll.end(), CEditValue(100));
    std::copy( coll.begin(), coll.end(), std::ostream_iterator<int>(std::cout, " ") );
 
    return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115