练习 c++ 特殊容器、特殊函数的使用

2014-11-24 09:28:14 · 作者: · 浏览: 0

//specialcontainer.cpp

[cpp]
/*一般容器:stack,queue

特殊容器:priority_queue

.push(element),.pop(),.empty()

stack:.top()

queue:.front(),.back()

priority_queue:.top()

没有迭代器

*/

#include

#include

using namespace std;

int main()

{

priority_queue pq;

pq.push(40);

pq.push(20);

pq.push(10);

pq.push(50);

pq.push(90);

while(!pq.empty())

{

cout<
pq.pop();

}

cout<




return 0;

}

//specialfunctions.cpp

[cpp] view plaincopyprint
/*一些特殊函数的用法

for_each()

copy()

copy_backward()

sort()

remove_copy_if()

find()

find_if()

count_if()

*/

#include

#include

#include

#include

#include

#include "print.h"

using namespace std;

void add10(int& element)

{

element+=10;

}

string printe(int element)

{

cout<
return "ok";

}

class add

{

int inc;

public:

add(int d):inc(d){}

void operator()(int& element)

{

element+=inc;

}

};

template

void foreach(Iter ib,Iter ie,Func f)//与for_each功能一样

{

while(ib!=ie) f(*ib++);

}

template

void co(Iter ib,Iter ie,Pos p)//与copy一样功能

{

while(ib!=ie) *(p++)=*(ib++);

}

bool func(int n)

{

return n&1;//偶数为1

}

bool is_upper(const string& str)

{

return isupper(str[0]);//大写开头

}

bool is_has_o(const string& str)

{

return str.find_first_of("oO")!=string::npos;//以o开头的

}

int main()

{

int a[5]={4,2,6,8,9};

int b[8]={0};

vector vt(a,a+5);

for_each(a,a+5,add10);

for_each(a,a+5,printe);cout<
for_each(a,a+5,add(4));//用add类实现想加多少就加多少

for_each(a,a+5,printe);cout<
sort(vt.begin(),vt.end());

print(vt.begin(),vt.end());

copy(vt.begin(),vt.end(),a);//把vt中的数据复制到a中去

print(a,a+5,',');

copy_backward(a,a+5,b+8);//把a中5个数据放到最后b的5个里面

print(b,b+8);

vector v2;

remove_copy_if(a,a+5,back_inserter(v2),func);//后插入

//remove_copy_if(a,a+5,front_inserter(v2),func);//前插入,适用于deque

print(v2.begin(),v2.end());

string str[5]={"kk","hj","fg","sd","ad"};

string *p=find(str,str+5,"sd");

cout<<(p==str+5 "not find ":"find ")<<"sd"<
p=find_if(str,str+5,is_upper);

cout<<(p==str+5 "not find ":"find ")<<"upper first "<
cout<
return 0;

}

//print.h

[cpp]
//print.h

#include

using namespace std;

#ifndef print_fun

#define print_fun

template

///显示序列数据

void print(T b,T e,char c=' ')

{

bool isExit=false;

while (b!=e)

{

cout<<*b++<
isExit=true;

}

if(isExit) cout<


}

template

ostream& operator<<(ostream& o,const pair& p)//重载输出map类型元素

{

return o<
}

#endif