STL for_each
时间:2010-10-25 来源:wrtrtew
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
// STL函数for_each(),sort(),random_shuffle()....
using namespace std;
struct Book{
string title;
int price;
};
void showBook(Book &b){
cout << "书名: 《" << b.title << "》 价格: " << b.price << endl;
};
bool compareBook(const Book & b1, const Book & b2){
if (b1.price >= b2.price){// 这里只处理了价格排序
return true;
}else
return false;
}
int main()
{
Book books[]={{"C Primer Plus",45}, {"C++ Primer Plus",54}, {"深度探索C++对象模型",40}};
vector<Book> mybooks;// 声明一个空容器变量
int i;
for (i=0; i < sizeof(books)/sizeof(Book); i++){
mybooks.push_back(books[i]);// 向容器尾部插入元素
};
cout << "顺序输出:" << endl;
for_each(mybooks.begin(), mybooks.end(), showBook);// 使用STL函数for_each()
cout << "排序输出:" << endl;
sort(mybooks.begin(), mybooks.end(), compareBook);
for_each(mybooks.begin(), mybooks.end(), showBook);// 使用STL函数for_each()
cout << "乱序输出:" << endl;
random_shuffle(mybooks.begin(), mybooks.end());
for_each(mybooks.begin(), mybooks.end(), showBook);// 使用STL函数for_each()
return 0;
}
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
// STL函数for_each(),sort(),random_shuffle()....
using namespace std;
struct Book{
string title;
int price;
};
void showBook(Book &b){
cout << "书名: 《" << b.title << "》 价格: " << b.price << endl;
};
bool compareBook(const Book & b1, const Book & b2){
if (b1.price >= b2.price){// 这里只处理了价格排序
return true;
}else
return false;
}
int main()
{
Book books[]={{"C Primer Plus",45}, {"C++ Primer Plus",54}, {"深度探索C++对象模型",40}};
vector<Book> mybooks;// 声明一个空容器变量
int i;
for (i=0; i < sizeof(books)/sizeof(Book); i++){
mybooks.push_back(books[i]);// 向容器尾部插入元素
};
cout << "顺序输出:" << endl;
for_each(mybooks.begin(), mybooks.end(), showBook);// 使用STL函数for_each()
cout << "排序输出:" << endl;
sort(mybooks.begin(), mybooks.end(), compareBook);
for_each(mybooks.begin(), mybooks.end(), showBook);// 使用STL函数for_each()
cout << "乱序输出:" << endl;
random_shuffle(mybooks.begin(), mybooks.end());
for_each(mybooks.begin(), mybooks.end(), showBook);// 使用STL函数for_each()
return 0;
}
相关阅读 更多 +