BOOST学习笔记

1 tool

 #pragma once
#include <vector> #include "boost/noncopyable.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/serialization/singleton.hpp" #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
using namespace boost;
using namespace std;
using namespace boost::serialization;
class CNo_copy_class : public noncopyable
{
public:
CNo_copy_class() : a(){}
int a;
}; void no_copy_test()
{
CNo_copy_class c1;
//CNo_copy_class c2(c1);
} vector<int> func()
{
return vector<int>(, );
} void typeof_auto_test()
{
//decltype(20*3.0) x1 = 20*3.0;
BOOST_TYPEOF(*3.0) x2 = *3.0; BOOST_AUTO(&a, new double[]);
BOOST_AUTO(p, make_pair(, "string")); BOOST_AUTO(v ,func()); //注册自定义类型
BOOST_TYPEOF_REGISTER_TYPE(CNo_copy_class)
BOOST_AUTO( pdef, new CNo_copy_class());
cout<< typeid(pdef).name() << endl;
} typedef singleton<CNo_copy_class> origin; void singleton_test()
{
cout << origin::get_const_instance().a << endl;
//origin::get_const_instance().a = 5;
cout << origin::get_mutable_instance().a << endl;
origin::get_mutable_instance().a = ;
cout << origin::get_const_instance().a << endl;
}

2 file

 #pragma once
#include "boost/filesystem.hpp" using namespace boost;
using namespace std; void path_string_opt_test()
{
filesystem::path p1;
assert(p1.empty()); filesystem::path p2("c:/user/local/include/xx.js");
cout << p2.string() << endl; if (p2.has_stem()) //xx,文件名,无后缀
{
cout << p2.stem() << endl;
}
if (p2.has_extension()) //.js,文件名后缀
{
cout << p2.extension() << endl;
}
if (p2.has_filename()) //xx.js,文件全名,有后缀
{
cout << p2.filename() << endl;
}
if (p2.has_parent_path()) //c:/user/local/include,除去文件名的路径
{
cout << p2.parent_path() << endl;
} if (p2.has_root_name()) //windows路径为c:
{
cout << p2.root_name() << endl;
}
if (p2.has_root_directory()) //windows路径为/
{
cout << p2.root_directory() << endl;
}
if (p2.has_root_path()) //windows路径为c:/
{
cout << p2.root_path() << endl;
} //修改文件路径
cout << p2.replace_extension("hxx") << endl; //修改扩展名,修改后为c:/user/local/include/xx
cout << p2.replace_extension() << endl; //修改扩展名,修改后为c:/user/local/include/xx
cout << p2.remove_filename() << endl; //移除文件名,修改后为c:/user/local/include
} void GetModulePath()
{
char szPath[MAX_PATH];
GetModuleFileName( NULL, szPath, MAX_PATH );
cout << szPath << endl;
//输出:p:\workspace\proj\test\boost_test\build\src\Debug\BOOST_TEST.exe cout << boost::filesystem::initial_path<filesystem::path>().string() <<endl;
//输出:p:\workspace\proj\test\boost_test\build\src //
cout << boost::filesystem::current_path().string() << endl;
} void directory_test()
{
boost::filesystem::path p1(boost::filesystem::current_path());
p1.append("123\\456");
//循环创建目录
if (!boost::filesystem::exists(p1))
{
boost::filesystem::create_directories(p1);
}
//递归删除最底层目录
if (boost::filesystem::exists(p1))
{
boost::filesystem::remove_all(p1);
}
}

3 container

 #pragma once
#include <map>
#include <vector>
#include "boost/array.hpp"
#include "boost/any.hpp"
#include "boost/foreach.hpp" using namespace boost;
using namespace std; void array_test()
{
array<int, > ar = {,};
array<string, > ars = {""};
for (int i=; i<; i++)
{
cout << ars[i] << endl;
}
} void any_test()
{
any a();
int n = any_cast<int>(a); any_cast<int&>(a) = ;
} void foreach_test()
{
int a[] = {, , , , , };
vector<int> vec(a , a + );
BOOST_FOREACH(int x, vec)
{
cout << x << endl;
}
BOOST_REVERSE_FOREACH(int x, vec)
{
cout << x << endl;
}
}

4 smart_ptr

 #pragma once
#include<iostream>
#include <vector>
#include "boost/smart_ptr.hpp"
using namespace boost;
using namespace std; //
void scoped_ptr_test()
{
scoped_ptr<int> p(new int);
if (p)
{
*p = ;
cout << *p << endl;
}
p.reset();
} void scoped_array_test()
{
scoped_array<int> p(new int[]);
fill_n(&p[], , );
p[] = p[] + p[];
} void shared_ptr_test()
{
shared_ptr<int> p(new int());
*p = ;
//shared_ptr< vector<int> > mp = make_shared< vector<int> >(100,5); //shardptr可以指定析构函数 } void shared_array_test()
{
shared_array<int> p(new int[]);
shared_array<int> p2 = p;
p[] = ;
assert( p2[] == );
} void weak_ptr_test()
{
shared_ptr<int> sp(new int());
assert(sp.use_count() == ); weak_ptr<int> wp(sp);
assert(wp.use_count() == ); if (!wp.expired())
{
shared_ptr<int> sp2 = wp.lock();
*sp2 = ;
assert(wp.use_count() == );
}
assert(wp.use_count() == );
sp.reset();
assert(wp.expired());
assert(!wp.lock());
}

5 function

 #pragma once
#include "boost/utility/result_of.hpp"
#include "boost/any.hpp"
#include "boost/bind.hpp"
#include "boost/function.hpp" using namespace boost;
using namespace std; template<typename T, typename T1>
typename result_of<T(T1)>::type call_func(T t, T1 t1)
{
return t(t1);
} void result_of_test()
{
typedef double (*Func)(double);
Func func = sqrt; result_of<Func(double)>::type x = func(5.0);
cout << typeid(x).name() << endl; any x2 = call_func(func, 5.0);
cout << typeid(boost::any_cast<double>(x2)).name() << endl;
} int f(int a, int b)
{
return a + b;
} int g(int a, int b, int c)
{
return a + b*c;
} void bind_test()
{
cout << bind(f, , )() << endl;
int x = , y = , z = ;
cout << bind(f, _1, )(x) << endl; //使用占位符
cout << bind(g, _3, _2, _2)(x, y, z) << endl; //使用占位符,乱序 //绑定成员函数
class demo
{
public:
int f(int a, int b)
{
cout << a << " "<< b << endl;
return a + b;
}
} a;
demo& b = a;
demo* p = &a;
cout << bind(&demo::f, a, _1, )() << endl;
cout << bind(&demo::f, b, _2, _1)(, ) << endl;
cout << bind(&demo::f, p, _1, _2)(, ) << endl; //算法容器
class point
{
public:
int x,y;
point() : x(), y() {}
void print()
{
cout << x << " " << y << endl;
}
};
std::vector<point> v();
for_each(v.begin(), v.end(), bind(&point::print, _1)); //成员函数_1表示函数指针
} void function_test()
{
boost::function<int(int, int)> func = f;
if (func)
{
cout << func(, ) << endl;
}
func.clear(); boost::function<int(int)> func1 = boost::bind(f, _1, );
if (func1)
{
cout << func1() << endl;
}
}

6 pool

 #pragma once
#include <vector>
#include "boost/pool/pool.hpp"
#include "boost/pool/object_pool.hpp"
#include "boost/pool/singleton_pool.hpp"
#include "boost/pool/pool_alloc.hpp"
using namespace boost;
using namespace std; class demo_class
{
public:
int a,b,c;
demo_class(int x = ,int y=, int z=):a(x), b(y), c(z)
{
}
};
typedef singleton_pool<demo_class , sizeof(demo_class)> spl; void pool_test()
{
pool<> pl(sizeof(int));
int* p = static_cast<int*>(pl.ordered_malloc());
assert(pl.is_from(p)); pl.ordered_free(p); for (int i=; i<; i++)
{
pl.ordered_malloc();
}
} void object_pool_test()
{
object_pool<demo_class> pl;
demo_class *p = pl.malloc();
assert(pl.is_from(p)); assert(p->a != || p->b != || p->c != ); p =pl.construct(, , );
assert(p->a == ); object_pool<std::string> pls;
for (int i=; i< ;i++)
{
std::string *ps = pls.construct("hello");
cout<< ps->c_str() << endl;
}
} void singleton_pool_test()
{
demo_class* p = (demo_class*)spl::malloc();
assert(spl::is_from(p));
spl::release_memory();
} void pool_alloc_test()
{
std::vector<int, pool_allocator<int> > v;
v.push_back();
}

7 thread

 #pragma once
#include <stack>
#include <vector>
#include "boost/thread.hpp"
#include "boost/foreach.hpp" using namespace boost;
using namespace std; boost::mutex io_mu_1;
void time_test()
{
this_thread::sleep_for(chrono::seconds()); this_thread::sleep_until(chrono::system_clock::now() + chrono::seconds());
} void to_interrupt(int& x, const string& str)
try
{
for (int i=; i<; i++)
{
boost::mutex::scoped_lock(io_mu_1);
cout << str << ++x << std::endl;
//this_thread::sleep_for(chrono::seconds(1));
{
//自动中断点 }
this_thread::interruption_point();
}
}
catch(...)
{
cout << "thread_interrupted" << std::endl;
}; void thread_test()
{
int x = ;
boost::thread t(to_interrupt, boost::ref(x), "hello");
this_thread::sleep_for(chrono::seconds()); t.interrupt();
assert(t.interruption_requested()); t.join();
} //测试条件变量
class buffer
{
public:
buffer(int n) : un_read(),capacity(n)
{
}
void put(int x)
{
{
boost::mutex::scoped_lock lock(mu);
while (if_full())
{
{
//boost::mutex::scoped_lock lock2(io_mu_1);
cout<< "full waiting\n";
}
cond_put.wait(mu);
}
}
stk.push(x);
++un_read;
cond_get.notify_one();
}
void get(int* x)
{
{
boost::mutex::scoped_lock lock(mu);
while (is_empty())
{
{
//boost::mutex::scoped_lock lock2(io_mu_1);
cout<< "empty waiting\n";
}
cond_get.wait(mu);
}
}
--un_read;
*x = stk.top();
stk.pop();
cond_put.notify_one();
}
private:
boost::mutex mu;
boost::condition_variable_any cond_put;
boost::condition_variable_any cond_get;
std::stack<int> stk;
int un_read,capacity;
bool if_full()
{
return un_read == capacity;
}
bool is_empty()
{
return un_read == ;
}
} buf(); void producer(int n)
{
for (int i=; i< n; i++)
{
{
//boost::mutex::scoped_lock lock(io_mu_1);
cout << "put " << i << std::endl;
}
buf.put(i);
}
} void consumer(int n)
{
int x;
for (int i=; i< n; i++)
{
buf.get(&x);
//boost::mutex::scoped_lock lock(io_mu_1);
cout << "get " << x << std::endl;
}
} void condition_test()
{
boost::thread t1(producer, );
boost::thread t2(consumer, );
boost::thread t3(consumer, ); t1.join();
t2.join();
t3.join(); boost::this_thread::sleep_for(boost::chrono::seconds());
} //共享互斥量
class rw_data
{
public:
rw_data() : m_x() {}
void write()
{
unique_lock<shared_mutex> ul(rw_mu);
++m_x;
}
void read(int* x)
{
shared_lock<shared_mutex> sl(rw_mu);
*x = m_x;
}
private:
int m_x;
shared_mutex rw_mu;
}; void writer(rw_data& d)
{
for (int i=; i< ; i++)
{
this_thread::sleep_for(chrono::milliseconds());
d.write();
}
} void reader(rw_data& d)
{
int x;
for (int i=; i< ; i++)
{
this_thread::sleep_for(chrono::milliseconds());
d.read(&x);
cout << this_thread::get_id()<< " read: "<<x<<std::endl;
}
} void shared_mutex_test()
{
rw_data d;
boost::thread_group pool;
pool.create_thread(bind(writer, boost::ref(d)));
pool.create_thread(bind(writer, boost::ref(d))); pool.create_thread(bind(reader, boost::ref(d)));
pool.create_thread(bind(reader, boost::ref(d)));
pool.create_thread(bind(reader, boost::ref(d)));
pool.create_thread(bind(reader, boost::ref(d))); pool.join_all();
this_thread::sleep_for(chrono::seconds());
} //future,线程返回执行结果
int fab(int n)
{
if (n == || n == )
{
return ;
}
return fab(n-) + fab(n-);
} void future_test()
{
//单个future
boost::packaged_task<int> pt(bind(fab, ));
boost::BOOST_THREAD_FUTURE<int> f = pt.get_future(); boost::thread(boost::move(pt));
f.wait(); cout << f.get() << endl;
this_thread::sleep_for(chrono::seconds()); //多个future协调,wait for all/any
typedef boost::packaged_task<int> pti_t;
typedef boost::BOOST_THREAD_FUTURE<int> fi_t; boost::array<pti_t, > ap;
boost::array<fi_t, > af; for (int i = ; i<;i++)
{
ap[i] = pti_t(bind(fab, i+ ));
af[i] = ap[i].get_future();
boost::thread(boost::move(ap[i]));
} boost::wait_for_all(af.begin(), af.end());
BOOST_FOREACH(fi_t& f, af)
{
cout << f.get() << endl;
} for (int i = ; i<;i++)
{
boost::thread(boost::move(ap[i]));
} boost::wait_for_any(af.begin(), af.end());
BOOST_FOREACH(fi_t& f, af)
{
if (f.is_ready() && f.has_value())
{
cout << f.get() << endl;
}
} this_thread::sleep_for(chrono::seconds());
} //线程本地存储
boost::thread_specific_ptr<int> pi; //本地线程存储一个int void printing()
{
pi.reset(new int()); ++(*pi);
cout << this_thread::get_id() << " thread, value = " << *pi << endl;
}
void tls_test()
{
(boost::thread(bind(printing)));
(boost::thread(bind(printing))); this_thread::sleep_for(chrono::seconds());
}

8 asio

8.1 server

 #pragma once
#include <vector> #include "boost/asio.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/smart_ptr.hpp" using namespace boost;
using namespace boost::asio;
using namespace std; boost::asio::io_service g_ios; //所有的asio都要有个ios //同步定时器
void deadlime_timer_sync_test()
{
boost::asio::deadline_timer t(g_ios, posix_time::seconds());
cout << t.expires_at() << endl; //终止绝对时间
t.wait();
} //异步定时器
//异步定时器回调标准格式
void print(system::error_code x)
{
cout << "deadline time\n";
} void deadlime_timer_async_test()
{
boost::asio::deadline_timer t(g_ios, posix_time::seconds());
cout << t.expires_at() << endl; //终止绝对时间
t.async_wait(print);
cout << "deadline time\n";
g_ios.run();
} //tcp
void tcp_address_test()
{
boost::asio::ip::address addr;
//addr = addr.from_string("ab.12.23.34");
//assert(addr.is_v6());
addr = addr.from_string("127.0.0.1");
assert(addr.is_v4());
cout << addr.to_string() << endl;
ip::tcp::endpoint ep(addr, );
assert(ep.address() == addr);
assert(ep.port() == );
} //服务端
void server_test()
{
ip::tcp::acceptor acceptor(g_ios,
ip::tcp::endpoint(ip::tcp::v4(), )); while ()
{
ip::tcp::socket sock(g_ios);
acceptor.accept(sock); cout << "recv client: " << sock.remote_endpoint().address() << endl;
sock.write_some(boost::asio::buffer(std::string("hello"))); //发送数据
}
} //异步
typedef boost::shared_ptr<ip::tcp::socket> sock_ptr;
class server
{
public:
server() : acceptor(g_ios,
ip::tcp::endpoint(ip::tcp::v4(), ))
{
start();
}
void start()
{
sock_ptr sock(new ip::tcp::socket(g_ios));
acceptor.async_accept(*sock,
bind(&server::accept_handler, this, asio::placeholders::error, sock));
}
void accept_handler(const system::error_code& ec, sock_ptr sock)
{
if (ec)
{
return;
}
cout << sock->remote_endpoint().address() << endl;
sock->async_write_some(boost::asio::buffer(std::string("hello")),
bind(&server::write_handler, this, asio::placeholders::error));
start();
}
void write_handler(const system::error_code& ec)
{
cout << "send msg ok\n";
}
private:
ip::tcp::acceptor acceptor;
}; void async_server_test()
{
server ser;
g_ios.run();
} void DNS_test()
{
ip::tcp::socket sock(g_ios);
ip::tcp::resolver rlv(sock.get_io_service()); ip::tcp::resolver::query qry("www.baidu.com", lexical_cast<std::string>());
ip::tcp::resolver::iterator iter = rlv.resolve(qry);
ip::tcp::resolver::iterator end; system::error_code ec = error::host_not_found;
for ( ; ec && iter != end; ++iter)
{
sock.close();
sock.connect(*iter, ec);
}
if ( ec )
{
cout << "can't connect\n";
}
}

8.2 client

 #pragma once
#include <vector> #include "boost/thread.hpp"
#include "boost/asio.hpp"
#include "boost/date_time/posix_time/posix_time.hpp" using namespace boost;
using namespace boost::asio;
using namespace std; boost::asio::io_service g_ios; //所有的asio都要有个ios //客户端
void client_test()
{
while ()
{
ip::tcp::socket sock(g_ios);
ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), );
sock.connect(ep); std::string str;
str.resize(, );
sock.read_some(buffer(str));
cout << "receive from " << sock.remote_endpoint().address() << endl;
cout << "content : " << str << endl; sock.close(); boost::this_thread::sleep_for(boost::chrono::seconds());
} } //异步通信客户端
typedef boost::shared_ptr<ip::tcp::socket> sock_ptr;
typedef boost::shared_ptr<std::string> str_ptr;
class client
{
public:
client() : ep(ip::address::from_string("127.0.0.1"), )
{
start();
}
void start()
{
sock_ptr sock(new ip::tcp::socket(g_ios));
sock->async_connect(ep,
bind(&client::connect_handler, this, asio::placeholders::error, sock));
}
void connect_handler(const system::error_code& ec,
sock_ptr sock)
{
if (ec)
{
return;
}
cout << "sock connect " << sock->remote_endpoint().address() << endl;
str_ptr pstr(new std::string(,));
sock->async_read_some(asio::buffer(*pstr),
bind(&client::read_hander, this, asio::placeholders::error, pstr));
start();
}
virtual void read_hander(const system::error_code& ec,
shared_ptr<std::string> str)
{
cout <<"recv msg: " <<str << endl;
}
protected:
ip::tcp::endpoint ep;
}; class client11 : public client
{
virtual void read_hander(const system::error_code& ec,
shared_ptr<std::string> str)
{
cout <<"child recv msg: " <<str << endl;
}
}; void async_client_test()
{
client11 cli;
g_ios.run();
}

9 源码

  1-8的源码地址:https://download.csdn.net/download/honggangqianren/10538015

BOOST学习笔记的更多相关文章

  1. boost 学习笔记 2: timer

    boost 学习笔记 2: timer copy from:http://einverne.github.io/post/2015/12/boost-learning-note-2.html 1:ti ...

  2. boost 学习笔记 0: 安装环境

    boost 学习笔记 0: 安装环境 最完整的教程 http://einverne.github.io/post/2015/12/boost-learning-note-0.html Linux 自动 ...

  3. boost学习笔记(七)---date_time库

    date_time库的日期基于格里高利历,支持从1400-01-01到9999-12-31之间的日期计算 #define BOOST_DATE_TIME_SOURCE #include <boo ...

  4. Boost学习笔记(六) progress_display注意事项

    progress_display可以用作基本的进度显示,但它有个固有的缺陷:无法把进度显示输出与程序的输出分离. 这是因为progress_display和所有C++程序一样,都向标准输出(cout) ...

  5. Boost学习笔记(五) progress_display

    progress_display可以在控制台显示程序的执行进度,如果程序执行很耗费时间,那么它能够提供一个友好的用户界面 #include <boost\timer.hpp> #inclu ...

  6. Boost学习笔记(三) progress_timer

    progress_timer也是一个计时器,它继承自timer,会在析构时自动输出时间,省去timer手动调用elapsed()的工作,是一个用于自动计时相当方便的小工具. #include < ...

  7. Boost学习笔记(二) 时间与日期

    timer库概述 timer库包含三个组件:分别是计时器类timer.progress_timer和进度指示类progress_display timer 主要作用是计时,精确度是毫秒级.下面是一个简 ...

  8. Boost学习笔记(一) 什么是Boost

    Boost库是一个功能强大.构造精巧,跨平台.开源并且完全免费的C++程序库

  9. boost 学习笔记 1: lexical_cast

    参考原著地址:http://einverne.github.io/post/2015/12/boost-learning-note-1.html 转换对象要求 lexical_cast 对转换对象有如 ...

随机推荐

  1. javamail 发送邮件demo(文字与附件)

    package com.get.one; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multip ...

  2. 网络编程4 网络编程之FTP上传简单示例&socketserver介绍&验证合法性连接

    今日大纲: 1.FTP上传简单示例(详细代码) 2.socketserver简单示例&源码介绍 3.验证合法性连接//[秘钥加密(urandom,sendall)(注意:中文的!不能用)] 内 ...

  3. 找不到ifconfig命令

    对于新安装的系统,可能会缺少ifconfig命令,这是因为少安装了net-tools工具,所以只要安装上即可. yum install net-tools -y

  4. BLOCK方式实现OC程序中多个页面判定用户是否登录

    在程序中经常会遇到这种情况,用户刚进入我们软件的时候我们是无需要求用户登录的,但是在下面的页面中,例如收藏,购买等页面的时候,显然在多个页面需要多次判定用户是否登录.试着用block简单的实现了一下该 ...

  5. 洛谷 P2331 [SCOI2005]最大子矩阵

    洛谷 这一题,乍一眼看上去只想到了最暴力的暴力--大概\(n^4\)吧. 仔细看看数据范围,发现\(1 \leq m \leq 2\),这就好办了,分两类讨论. 我先打了\(m=1\)的情况,拿了30 ...

  6. Android-BoundService

    Android-BoundService 一 binder 内核->字符设备binder(负责进程间通信的驱动)->servicemanager->binder类->binge ...

  7. Selenium 安装与卸载

    安装: 在cmd中键入pip install selenium==3.6.0(等号后面的为版本号),并点击回车,当出现Successfully installed selenium-3.6.0即表示已 ...

  8. STL sort “invalid operator <”

    跟踪了下,是比较函数(下面的_Pred)的问题: template<class _Pr, class _Ty1, class _Ty2> inline bool _Debug_lt_pre ...

  9. 转:[NHibernate]视图处理

    转自:http://www.cnblogs.com/wolf-sun/p/4082899.html 目录 写在前面 文档与系列文章 视图 一个例子 总结 写在前面 前面的文章主要讲了对物理数据表的操作 ...

  10. HBase在数据统计应用中的使用心得

    转载自:http://www.cnblogs.com/panfeng412/archive/2011/11/19/2254921.html 1. 数据统计的需求 互联网上对于数据的统计,一个重要的应用 ...