1、for_each()遍历
示例(foreach):
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
template<typename T>
void zsshow(const T& no)
{
cout << "亲爱的" << no << "号:我是一只傻傻鸟。\n";
}
template<typename T>
class czs
{
public:
void operator()(const T& no) {
cout << "亲爱的" << no << "号:我是一只傻傻鸟。\n";
}
};
template<typename T1, typename T2>
void foreach(const T1 first, const T1 last, T2 pfun)
{
for (auto it = first; it != last; it++)
pfun(*it);
}
int main()
{
vector<int> bh = { 5,8,2,6,9,3,1,7 };
foreach(bh.begin(), bh.end(), zsshow<int>);
foreach(bh.begin(), bh.end(), czs<int>());
}
2、find_if
#pragma region find_if
template<typename T>
bool findLike(const T& no) {
if (no == 3)
{
cout << "亲爱的" << no << "我找到你了" << endl;
return true;
}
else
{
return false;
}
}
template<typename T>
class czs2
{
public:
T t_no;
czs2(const T & no):t_no(no){}
bool operator()(const T& no) {
if (no ==t_no)
{
cout << "亲爱的" << no << "我找到你了" << endl;
return true;
}
else
{
return false;
}
}
private:
};
template<typename T1,typename T2>
T1 findif(const T1 first, const T1 last, T2 pfun) {
for (auto it = first; it != last; it++)
if (pfun(*it)==true) return it;
return last;
}
#pragma endregion
int main() {
list<int> bh = { 5,3,6,1 };
auto it1= find_if(bh.begin(), bh.end(), findLike<int>);
if (it1 == bh.end()) cout << "查找失败" << endl;
else cout << "查找成功" <<*it1<< endl;
auto it2 = find_if(bh.begin(), bh.end(), czs2<int>(3));
if (it1 == bh.end()) cout << "查找失败" << endl;
else cout << "查找成功" << *it1 << endl;
system("pause");
}
3、bsort
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>
using namespace std;
template<typename T>
bool compasc(const T& left, const T& right) {
return left < right;
}
template<typename T>
struct _less
{
bool operator()(const T& left, const T& right) {
return left < right;
}
};
template<typename T>
bool compdesc(const T& left, const T& right) {
return left > right;
}
template<typename T>
class _greater
{
public:
bool operator()(const T& left, const T& right) {
return left > right;
}
};
template<typename T, typename compare>
void bsort(const T first, const T last, compare comp)
{
while(true)
{
bool bswap = false;
for (auto it = first; ; )
{
auto left = it;
it++;
auto right = it;
if (right == last) break;
if (comp(*left, *right) == true) continue;
auto tmp = *right;
*right = *left;
*left = tmp;
bswap = true;
}
if (bswap == false) break;
}
}
int main()
{
vector<int> bh = { 5,8,2,6,9,33,1,7 };
sort(bh.begin(), bh.end(), _greater<int>());
for (auto val : bh)
cout << val << " ";
cout << endl;
}