count 的应用:
#include <iostream>
#include <vector>
#include <algorithm> //泛型算法头文件
using namespace std;
int main()
{
int ival,searchValue;
vector<int> ivec;
cout<<"enter some inlegers(crel+z to end):"<<endl;
while(cin>>ival)
ivec.push_back(ival);//装入数组中
cin.clear();
cout<<"enter an integer you want to scarch :"<<endl;
cin>>searchValue;
cout<<count(ivec.begin(),ivec.end(),searchValue)//如何找到,返回数字出现的次数.否则,返回0
<<"elements int the vector have value"
<<searchValue<<endl;
for(int i=0;i<ivec.size();i++) //如果是string,用length方法可以返回单个元素的字符长度
{
cout<<ivec[i]<<endl;
}
return 0;
}
运行结果:
list的应用:
#include <iostream>
#include <string>
#include <list>
#include <algorithm> //泛型算法头文件
using namespace std;
int main()
{
string ival,searchValue;
list<string> ivec;
cout<<"enter some inlegers(crel+z to end):"<<endl;
while(cin>>ival)
ivec.push_back(ival);//装入数组中
cin.clear();
cout<<"enter an integer you want to scarch :"<<endl;
cin>>searchValue;
cout<<count(ivec.begin(),ivec.end(),searchValue)//如何找到,返回数字出现的次数.否则,返回0
<<"elements int the vector have value"
<<searchValue<<endl;
cout<<ivec.size()<<endl;//返回ivec中数组的个数
list<string>::iterator it; //迭代器
for(it=ivec.begin(); it!=ivec.end(); it++)
{
cout<<*it<<" "<<endl;
}
ivec.sort();
for(it=ivec.begin(); it!=ivec.end(); it++)
{
cout<<*it<<" "<<endl;
}
return 0;
}
运行结果:
push_back,push_front,count_if的用法:
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
void PrintIt(string StringToPrint) {
cout << StringToPrint << endl;
}
bool lengths(string StringToPrint)
{
if(StringToPrint.length()>5)
{
return true;
}
else
{
return false;
}
}
int main() {
int num=0,leng=0;
list<string> FruitAndVegetables;
FruitAndVegetables.push_back("carrot");
FruitAndVegetables.push_back("pumpkin");
FruitAndVegetables.push_back("potato");
FruitAndVegetables.push_front("apple");
FruitAndVegetables.push_front("pineapple");
for_each(FruitAndVegetables.begin(), FruitAndVegetables.end(), PrintIt);
num=count(FruitAndVegetables.begin(),FruitAndVegetables.end(),"apple");
cout<<num<<endl;
leng=count_if(FruitAndVegetables.begin(),FruitAndVegetables.end(),lengths);
cout<<leng<<endl;
return 0;
}
运行结果:
综上总结:
(1) list的成员函数push_back()把一个对象放到一个list的后面,而 push_front()把对象放到前面。
(2) 知道一个list是否为空很重要。如果list为空,empty()这个成员函数返回真。
(3) 这个list容器,就象你所想的,它不支持在iterator加一个数来指向隔一个的对象。 就是说,我们不能用ivec.begin()+2来指向list中的第三个对象,因为STL的list是以双链的list来实现的, 它不支持随机存取。vector和deque(向量和双端队列)和一些其他的STL的容器可以支持随机存取。
(4) 对于count,当然也可以对int数值进行查找计数,这个视具体情况而定。count_if()通过传递一个函数对象来作出比count()更加复杂的评估以确定一个对象是否应该被记数。
(5)对于输出一个容器中的元素时,for_each是一个不错的选择。
(6)end指向的是容器中最后一个元素的下一个存储空间,所以,不要轻易访问,这样就访问了非法内存,类似与: