STL算法-for-each
#define _CRT_SECUER_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<list>
#include<map>
using namespace std;
void foreach(const vector<int>& v) {
for (auto it = v.begin();it != v.end();it++) {
cout << "亲爱的" << *it << "号:我是一只小小鸟\n";
}
}
void foreach(const vector<int>::iterator first, const vector<int>::iterator last) {
for (auto it = first;it != last;it++) {
cout << "亲爱的" << *it << "号:我是一只小小鸟\n";
}
}
int main() {
vector<int>bh = { 5,4,9,5,7,8 };
//foreach(bh);
foreach(bh.begin()+2,bh.end()-1);
}
如果说这个vector中装的是string类型,那么这个迭代器函数就不能用了,所以我们可以直接弄成一个模板函数
然后就可以了
#define _CRT_SECUER_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<list>
#include<map>
using namespace std;
void foreach(const vector<int>& v) {
for (auto it = v.begin();it != v.end();it++) {
cout << "亲爱的" << *it << "号:我是一只小小鸟\n";
}
}
template<typename T>
void foreach(const T first, T last) {
for (auto it = first;it != last;it++) {
cout << "亲爱的" << *it << "号:我是一只小小鸟\n";
}
}
int main() {
list<int>bh = { 5,4,9,5,7,8 };
vector<string>ve = { "05","04","09","07","08" };
//foreach(bh);
foreach(bh.begin(),bh.end());
foreach(ve.begin(), ve.end());
}
然后我们在foreach中自定义表白函数
#define _CRT_SECUER_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<list>
#include<map>
using namespace std;
void foreach(const vector<int>& v) {
for (auto it = v.begin();it != v.end();it++) {
cout << "亲爱的" << *it << "号:我是一只小小鸟\n";
}
}
template<typename T1>
void zzshow(const T1 &no) {
cout << "亲爱的" << no << "号:我是一只小小鸟\n";
}
template<typename T, typename T1>
void foreach(const T first, T last,T1 pfun) {
for (auto it = first;it != last;it++) {
pfun(*it);
}
}
int main() {
list<int>bh = { 5,4,9,5,7,8 };
vector<string>ve = { "05","04","09","07","08" };
//foreach(bh);
foreach(bh.begin(), bh.end(), zzshow<int>);
foreach(ve.begin(), ve.end(),zzshow<string>);
}
STL算法-sort
#define _CRT_SECUER_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<list>
#include<map>
using namespace std;
template<typename T>
bool compasc(const T& left, const T& right) {
if (left < right) return true;
return false;
}
template<typename T>
bool compdesc(const T& left, const T& right) {
if (left > right) return true;
return false;
}
int main() {
vector<string>ve = { "05","04","09","07","08" };
sort(ve.begin(), ve.end(),compdesc<string>);
}