STL提供了一组表示容器、迭代器、函数对象和算法的模板。容器是一个与数组类似的单元,是同质的(既存储的值类型相同);算法是完成特定任务的prescription;迭代器是用来遍历容器的对象;函数对象是类似于函数的对象,可以是类对象或者函数指针。
模板类vector
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
struct stu
{
string title;
int rating;
};
bool Fillstu(stu& s);
void Showstu(const stu& s);
bool operator<(const stu& s1,const stu& s2);
bool temp1(const stu& s1,const stu& s2);
int main()
{
vector<stu> books;
stu tempp;
while(Fillstu(tempp))
books.push_back(tempp);
int num = books.size();
cout<<"Book size: "<<books.size();
vector<stu> books2(books);
cout<<"Rating\tbooks\n";
for(int i=0;i<num;i++)
{
cout<<books[i].rating<<"\t"<<books[i].title<<endl;
}
vector<stu>::iterator st; //迭代器
cout<<"Using iterator:\n" ;
cout<<"Rating\tbooks\n";
for(st=books.begin();st!=books.end();st++)
{
Showstu(*st) ;
}
books.erase(books.begin()+1,books.begin()+3);
cout<<"After erasing\n";
for_each(books.begin(),books.end(),Showstu);
books.insert(books.begin(),books2.begin(),books2.begin()+2);
cout<<"After inserting\n";
cout<<"Rating\tbooks\n";
for_each(books.begin(),books.end(),Showstu);
books.swap(books2);
cout<<"After swapping\n";
cout<<"Rating\tbooks\n";
for(auto x:books) Showstu(x);
sort(books.begin(),books.end());
cout<<"Aftering sort with 2 parameter\n";
cout<<"Rating\tbooks\n";
for(auto x:books) Showstu(x);
random_shuffle(books.begin(),books.end()) ;
cout<<"After random shuffle:\n";
cout<<"Rating\tbooks\n";
for(auto x:books) Showstu(x);
sort(books.begin(),books.end(),temp1);
cout<<"Aftering sort with 3 parameter\n";
cout<<"Rating\tbooks\n";
for(auto x:books) Showstu(x);
}
bool operator<(const stu& s1,const stu& s2)
{
if(s1.title<s2.title)
return true;
else if(s1.title == s2.title && s1.title<s2.title )
return true;
else
return false;
}
bool Fillstu(stu& s)
{
cout<<"Enter book title(quit to quit): ";
getline(cin,s.title);
if(s.title =="quit")
return false;
cout<<"Enter book rating: ";
cin>>s.rating;
if(!cin)
return false;
while(cin.get()!='\n')
continue;
return true;
}
void Showstu(const stu& s)
{
cout<<s.rating<<"\t"<<s.title<<endl;
}
bool temp1(const stu& s1,const stu& s2)
{
if(s1.rating<s2.rating)
return true;
else
return false;
}
- for_each() 和 random_shuffle()函数在头文件algorithm中
- 2个参数的sort()函数需要有定义operator<()函数来比较相关的元素。
- 3个参数的sort()函数需要定义一个比较相关元素的函数