STL_Algorithm5-math: random_shuffle, count, count_if, min_element, max_element, accumulate, for_each, transform

 

 

// Math.cpp : Defines the entry point for the console application.

//

 

 

#include <iostream>

#include <algorithm>

#include <numeric>

#include <vector>

#include <iterator>

 

using std::cout;

using std::endl;

 

bool greater9( int );

void outputSquare( int );

int calculateCube( int );

 

int main()

{

    const int SIZE = 10;

    int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 

    std::vector< int > v( a1, a1 + SIZE );

    std::ostream_iterator< int > outputIt( cout, " " );

 

    cout<<"Vector v before random_shuffle: ";

    std::copy( v.begin(), v.end(), outputIt );

 

    std::random_shuffle( v.begin(), v.end() );

 

    cout<< "/nVector v after random_shuffle: ";

    std::copy( v.begin(), v.end(), outputIt );

 

    int a2[] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 };

    std::vector< int > v2( a2, a2 + SIZE );

 

    cout<<"/n/nVector v2 contains: ";

    std::copy( v2.begin(), v2.end(), outputIt );

 

    int result = std::count( v2.begin(), v2.end(), 8 );

 

    cout<<"/nNumber of elements matching 8: "<<result;

 

    result = std::count_if( v2.begin(), v2.end(), greater9 );

 

    cout<<"/nNumber of elements greater than 9: "<<result;

 

    cout<<"/n/nMinimum element in Vector v2 is: "

        <<*(std::min_element( v2.begin(), v2.end() ) );

 

    cout<<"/n/nMaxmum element in Vector v2 is: "

        <<*(std::max_element( v2.begin(), v2.end() ) );

 

    cout<<"/n/nThe total of the elements in Vector v is: "

        << std::accumulate( v.begin(), v.end(), 0 );

 

    cout<< "/n/nThe square of every integer in Vector v is:/n";

 

    std::for_each( v.begin(), v.end(), outputSquare );

 

    std::vector< int > cubes( SIZE );

 

    std::transform( v.begin(), v.end(), cubes.begin(), calculateCube );

 

    cout<< "/n/nThe cube of every integer in Vector v is:/n";

    std::copy( cubes.begin(), cubes.end(), outputIt );

 

    cout<<endl;

 

return 0;

}

 

bool greater9( int value )

{

    return value > 9;

}

 

void outputSquare( int value )

{

    cout<<value * value<< ' ';

}

 

int calculateCube( int value )

{

    return value*value*value;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值