(1)全局函数在容器中加入,不用带参数;
for_each(vec.begin(),vec.end(),Display); //1.全局函数在容器中加入,不用带参数;
(2) 仿函数在容器中加入,不用带参数;
for_each(vec.begin(),vec.end(),CDisplay()); //2.仿函数在容器中加入,不用带参数;
(3)lamabda函数在容器中加入,带参数; //a.lamabda()表达式和仿函数无关
for_each(vec.begin(),vec.end(),[](int(n)){
//3.lamabda函数在容器中加入,带参数; //a.lamabda()表达式和仿函数无关
cout<<n<<"\t";});
(完整代码 001_for_each.cpp)
#include
#include
#include
#include
#include
#include
using namespace std;
class CDisplay{
public:
void operator()(int n){
cout << n << "\t";
}
};
void Display(int n){
cout << n << "\t";
}
int main()
{
vector<int> vec{
1,2,3,4,5,6};
for_each(vec.begin(),vec.end(),Display); //1.全局函数在容器中加入,不用带参数;
cout << endl;
for_each(vec.begin(),vec.end(),CDisplay()); //2.仿函数在容器中加入,不用带参数;
cout << endl;
for_each(vec.begin(),vec.end(),[](int(n)){
//3.lamabda函数在容器中加入,带参数; //a.lamabda()表达式和仿函数无关
cout<<n<<"\t";});
cout << endl;
cout << "----------------------"<<endl;
list<int> li{
11,12,13,14,15,16};
for_each(li.begin(),li.end(),Display); //1.全局函数在容器中加入,不用带参数;
cout << endl;
for_each(li.begin(),li.end(),CDisplay()); //2.成员函数在容器中加入,不用带参数;
cout << endl;
cout << "----------------------"<<endl;
set<int> s{
31,32,33,34,35,36};
for_each(s.begin(),s.end(),Display); //1.全局函数在容器中加入,不用带参数;
cout << endl;
for_each(s.begin(),s.end(),CDisplay()); //2.成员函数在容器中加入,不用带参数;
cout << endl;
cout << "----------------------"<<endl;
map<int,string> records{
{
1,"张三"}, {
2,"李四"}, {
3,"王五"}
};
for_each(records.begin(),records.end(),[](pair<int,string> p){
cout<<p.first <<"\t"<<p.second<<endl;});
return 0;
}
查找数组,字符串数组的最小值,注意比较对象max(a,b);
cout << max(1.2,1.3)<< endl;
cout << min("abc","abd")<< endl;//查找数组,字符串数组的最小值,注意比较对象max(a,b);
(1)distance获取顺序容器中的最值,注意解引用;
采用迭代器的方式(auto查找)
list<double> l{
1.1,1.2,1.3};
auto max_it = max_element(l.begin(),l.end());
cout << distance(l.begin(),max_it) << "\t" << *max_it << endl;
auto min_it = min_element(l.begin(),l.end());
cout << distance(l.begin(),min_it) << "\t" << *min_it << endl;
(完整代码见002_max_min.cpp)
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
cout << max(1.2,1.3)<< endl;
cout << min("abc","abd")<< endl;//查找数组,字符串数组的最小值,注意比较对象max(a,b);
//获取顺序容器中的最值,注意解引用;
list<double> l{
1.1,1.2,1.3};
auto max_it = max_element(l.begin(),l.end());
cout << distance(l.begin(),max_it) << "\t" << *max_it << endl;
auto min_it = min_element(l.begin(),l.end());
cout << distance(l.begin(),min_it) << "\t" << *min_it << endl;
return 0;
}
a.容器对象:vector,deque,默认升序
sort(vec.begin(),vec.end()