最近项目中使用了boost的库,于是想把它学得更好,这里写点基础的用法,方便大家使用,虽然简单但是很实用。当然可以分析源码的高手就不用看这些东西了。使用的库为boost1.55版本。今天先从bind讲起吧,这个东西可以将函数的参数变为比原来参数个数少的函数,也可以找到类成员函数的指针。
好了以上坑爹的讲解完毕,发出代码来!
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstring>
void add(int i, int j)
{
std::cout << i + j << std::endl;
}
bool compare(int i, int j)
{
return i > j;
}
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
std::for_each(v.begin(), v.end(), boost::bind(add, 10,_1));
std::sort(v.begin(), v.end(), boost::bind(compare, _1, _2));
std::for_each(v.begin(), v.end(), boost::bind(add, 10, _1));
boost::function<int(const char*)> f = std::atoi;
std::cout << f("1609") << std::endl;
f = std::strlen;
std::cout << f("1609") << std::endl;
system("pause");
}
这里给出了bind和function的用法,虽然简单,但是希望大家可以尝试着去使用改代码进行开发。简化自己的程序从一点一滴做起,提高慢慢开始。好了,不熟悉stl库的童鞋麻烦先去看stl用法,这里不予讲解,来讲解下
最后啰嗦下 这表示一个模板函数,第一个int 代表函数是一个int型的返回值,括号中表示传入参数的类型是const char*!说明结束。
。