stl学习笔记7

// stl/foreach1.cpp
/*
函数作为算法的参数
*/

#include 
< iostream >
#include 
< vector >
#include 
< algorithm >
using   namespace  std;

void  print( int  elem)
{
    cout 
<<elem<<' ';
}


int  main()
{
    vector
<int>  coll;

    
for(int i = 1; i<=9++i)
    
{
        coll.push_back(i);
    }


    
// print 函数作为算法的参数
    for_each(coll.begin(),coll.end(),print);
    
// 这里 for_each函数对 begin - end 区间内的每个元素调用print 函数。
    cout <<endl;
}


//  Output Result
/*
1 2 3 4 5 6 7 8 9
*/

 

 

// stl/print.h
#include  < iostream >

/*
** PRINT_ELEMENTS()
** print all element int zhe collection coll followed by a C_Style String
*/

template 
< class  T >
inline 
void  PRINT_ELEMENTS( const  T &  coll, const   char *  optcstr  =   "   " )
{
    typename T::const_iterator pos;

    cout 
<< optcstr;

    
for(pos = coll.begin();pos!= coll.end();++pos)
    
{
        cout 
<<*pos << ' ';
    }

    cout 
<<endl;
}

 

#include  < iostream >
#include 
< vector >
#include 
< set >
#include 
< algorithm >
#include 
" print.h "

using   namespace  std;


int  squre( int  value)
{
    
return value*value;
}


int  main()
{
    
set<int> coll_set;
    vector
<int> coll_vect;

    
for(int i =1; i<=9;++i)
    
{
        coll_set.insert(i);
    }


    
// print
    PRINT_ELEMENTS(coll_set,"initialized: ");
    transform(coll_set.begin(),coll_set.end(),back_inserter(coll_vect),squre);
    
//print
    PRINT_ELEMENTS(coll_vect,"squared: ");
}


// Output Result
/*
initialized: 1 2 3 4 5 6 7 8 9
squared: 1 4 9 16 25 36 49 64 81
*/

 

判断式的例子

// stl/prime1.cpp

//  predicates(判断式),就是返回boolean 值得函数,通常用来指定排序准则,或者搜寻准则。
//  一元判断式及二元判断式,二元的例子以后再写啦

//
//  Unary Predicates(一元判断式)
//
#include  < iostream >
#include 
< list >
#include 
< algorithm >
#include 
< cstdlib >   //  using function abs()
using   namespace  std;

//  判断某个数是不是质数
bool  isPrime( int  number)
{
    number 
= abs(number);

    
if(number ==0||number ==1)
        
return true;

    
int divisor;

    
for(divisor = number/2; number%divisor !=0;--divisor);

    
return divisor ==1;
}


int  main()
{
    list
<int> coll;

    
for(int i =24; i<=30;++i)
    
{
        coll.push_back(i);
    }


    list
<int>::iterator pos;

    
// find_if algorithm
    pos = find_if(coll.begin(),coll.end(),isPrime);

    
if(pos != coll.end())
        cout 
<<*pos << " is first prime number found" <<endl;
    
else
        cout 
<<"no prime number found"<<endl;
}

//  Output 
/*
**  29 is first prime number found
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值