bind1st/bind2nd简单用法
#include <iostream>
#include <vector>
#include <algorithm>
#include<functional>
#include <ctime>
using namespace std;
template<typename Container>
void showContainer(Container conn)
{
typename Container::iterator it = conn.begin();
for (; it != conn.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
vector<int> vec;
srand(time(nullptr));
for (int i = 0; i < 20; ++i)
{
vec.push_back(rand() % 100 + 1);
}
showContainer(vec);
sort(vec.begin(), vec.end());
showContainer(vec);
sort(vec.begin(), vec.end(), greater<int>());
auto it1 = find_if(vec.begin(), vec.end(), bind1st(greater<int>(), 70));
auto it2 = find_if(vec.begin(), vec.end(), bind1st(less<int>(), 70));
if (it1 != vec.end())
{
vec.insert(it1, 70);
}
return 0;
}
bind1st/bind2nd底层实现
template<typename Iterator, typename Compare>
Iterator my_find_it(Iterator first, Iterator last, Compare comp)
{
for (; first != last; ++first)
{
if (comp(*first))
{
return first;
}
}
return last;
}
template<typename Compare,typename T>
class _mybind1st
{
public:
_mybind1st(Compare comp, T val)
:_comp(comp)
, _val(val)
{
}
bool operator()(const T& second)
{
return _comp(_val, second);
}
private:
Compare _comp;
T _val;
};
template<typename Compare , typename T>
_mybind1st<Compare,T> mybind1st(Compare comp, const T& val)
{
return _mybind1st<Compare, T>(comp, T);
}
function函数保留类型
#include <iostream>
#include <vector>
#include <algorithm>
#include<functional>
#include <ctime>
#include <string.h>
using namespace std;
void hello1()
{
cout << "hello world" << endl;
}
void hello2(string str)
{
cout << str << endl;
}
int sum(int a, int b)
{
return a + b;
}
class Test
{
public:
void hello(string str)
{
cout << hello << endl;
}
private:
};
int main()
{
function<void()> func1 = hello1;
function<void()> func2(hello1);
function<void(string)> func3 = hello2;
func3("hello hello3");
func1();
function<int(int, int)> func4 = sum;
cout << func4(20, 30) << endl;
function<int(int, int)> func5 = [](int a, int b)->int {return a + b; };
cout << func5(100, 50) << endl;
function<void(Test*, string)> func6 = &Test::hello;
func6(&Test(), "Hello func6");
return 0;
}
function应用
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include<functional>
#include <ctime>
#include <string.h>
using namespace std;
void doShowAllBooks() { cout << "查看所有书籍信息" << endl; }
void doBorrow() { cout << "借书" << endl; }
void doBack() { cout << "还书" << endl; }
int main()
{
int choice = 0;
map<int, function<void()>> actionMap;
actionMap.insert({ 1,doShowAllBooks });
actionMap.insert({ 2,doBorrow });
actionMap.insert({ 3,doBack });
for (;;)
{
cout << "__________________" << endl;
cout << "1.查看所有书籍信息" << endl;
cout << "2.借书" << endl;
cout << "3.还书" << endl;
cout << "4.查询书籍" << endl;
cout << "5.注销" << endl;
cout << "__________________" << endl;
cout << "请选择" << endl;
cin >> choice;
auto it = actionMap.find(choice);
if (it == actionMap.end())
{
cout << "输入数字无效" << endl;
}
else
{
it->second();
}
}
}