练习 c++ 特殊容器、特殊函数的使用
//specialcontainer.cpp
[cpp]
/*一般容器:stack,queue
特殊容器:priority_queue
.push(element),.pop(),.empty()
stack:.top()
queue:.front(),.back()
priority_queue:.top()
没有迭代器
*/
#include<iostream>
#include<queue>
using namespace std;
int main()
{
priority_queue<int> pq;
pq.push(40);
pq.push(20);
pq.push(10);
pq.push(50);
pq.push(90);
while(!pq.empty())
{
cout<<pq.top()<<' ';
pq.pop();
}
cout<<endl;
return 0;
}
//specialfunctions.cpp
[cpp] view plaincopyprint?
/*一些特殊函数的用法
for_each()
copy()
copy_backward()
sort()
remove_copy_if()
find()
find_if()
count_if()
*/
#include<iostream>
#include<algorithm>
#include<string>
#include<cctype>
#include<vector>
#include "print.h"
using namespace std;
void add10(int& element)
{
element+=10;
}
string printe(int element)
{
cout<<element<<" ";
return "ok";
}
class add
{
int inc;
public:
add(int d):inc(d){}
void operator()(int& element)
{
element+=inc;
}
};
template<typename Iter,typename Func>
void foreach(Iter ib,Iter ie,Func f)//与for_each功能一样
{
while(ib!=ie) f(*ib++);
}
template<class Iter,class Pos>
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<int> vt(a,a+5);
for_each(a,a+5,add10);
for_each(a,a+5,printe);cout<<endl;
for_each(a,a+5,add(4));//用add类实现想加多少就加多少
for_each(a,a+5,printe);cout<<endl;
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<int> 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"<<endl;//str+5 说明没找到
p=find_if(str,str+5,is_upper);
cout<<(p==str+5?"not find ":"find ")<<"upper first "<<endl;//str+5 说明没找到
cout<<count_if(str,str+5,is_upper)<<endl;//统计符合条件的个数
return 0;
}
//print.h
[cpp]
//print.h
#include <iostream>
using namespace std;
#ifndef print_fun
#define print_fun
template<typename T>
///显示序列数据
void print(T b,T e,char c=' ')
{
bool isExit=false;
while (b!=e)
{
cout<<*b++<<c;
isExit=true;
}
if(isExit) cout<<endl;
}
template<typename K,typename V>
ostream& operator<<(ostream& o,const pair<K,V>& p)//重载输出map类型元素
{
return o<<p.first<<':'<<p.second;
}
#endif
补充:软件开发 , C++ ,