#include <iostream>
#include <vector>
#include <string>
#include <algorithm>//通用算法头文件
using namespace std;
void foreach(string str)
{
cout<<str<<endl;
}
bool isWorld(string& str)
{
if(str == "world")
{
return true;
}
return false;
}
void main()
{
cout<<"OK,JUST DO IT!!"<<endl;
vector<string> strA;
strA.push_back("I am the first string!");
strA.push_back("I am the second string!");
strA.push_back("I am the third string !");
strA.push_back("hello");
strA.push_back("world");
strA.push_back("hello");
strA.push_back("hello");
strA.push_back("world");
cout<<"for research strA---------------------------------"<<endl;
for( vector<string>::iterator it = strA.begin(); it != strA.end(); it++ )
{
cout<<*it<<endl;
}
cout<<"for_each research strA----------------------------"<<endl;
for_each(strA.begin(),strA.end(),foreach);
string dis = "hello";
int num = count( strA.begin(), strA.end(), dis );
cout<<"there are "<<num<<" of \"hello\" string!"<<endl;
//第三个参数可以是一个函数,还可以是一个类(含有operator),要求返回值要求均为bool型
num = count_if( strA.begin(), strA.end(), isWorld );
cout<<"there are "<<num<<" of \"world\" string!"<<endl;
string strWorld = "world";
//find前两个参数是iterator(迭代器),表示查找半闭合区间的前后两个位置
//第三个参数是于strA容器中相匹配的数据类型的一个对象
vector<string>::iterator itWorld = find( strA.begin(), strA.end(), strWorld);
if( itWorld != strA.end() )
{
cout<<"find "<<*itWorld<<endl;
}
else
{
cout<<"not find!"<<endl;
}
itWorld = find_if( strA.begin(), strA.end(), isWorld );
if( itWorld != strA.end() )
{
cout<<"find_if "<<*itWorld<<endl;
}
else
{
cout<<"not find_if!"<<endl;
}
vector<string> strSearch;
strSearch.push_back("hello");
strSearch.push_back("world");
//search()算法,它是搜索的一个范围,如果成功返回一个指着strA中第一个于strSearch匹配的iterator,否侧返回strA的end()
//find和find_if算法查找的是容器的第一个匹配的值
vector<string>::iterator itSearch = search( strA.begin(), strA.end(), strSearch.begin(), strSearch.end() );
if( itSearch != strA.end() )
{
cout<<"search success!"<<endl;
}
else
{
cout<<"search fail!"<<endl;
}
//sort()算法只使用于可以随机访问的类型,vector可以,list不可以,他有自己的sort算法
sort(strA.begin(),strA.end());
cout<<"after sort ----------------------------------------"<<endl;
for_each(strA.begin(),strA.end(),foreach);
}
评论0
最新资源