Boost的几个常用组件的使用(转载)

本文介绍了Boost库中几个实用的组件,包括boost::any、boost::array、boost::lexical_cast等,通过示例展示了它们的基本用法及优势,如类型安全、便捷的字符串转换、跨平台线程支持等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近也经常用到boost库,发现C++越来越多的amazing的特性。下面这些我在网上一个叫“小明思考”的blog上面找到的。我没有用过,不过感觉挺实用的。我接触过的组件有bind、option和datetime。有机会我将补充这几个组件的使用。现在太忙啦。

1.boost::any

boost::any是一种通用的数据类型,可以将各种类型包装后统一放入容器内
最重要的它是类型安全的。有点象COM里面的variant.

使用方法:
any::type() 返回包装的类型
any_cast可用于any到其他类型的转化

#include <boost/any.hpp>
void test_any()
{
 typedef std::vector<boost::any> many;
 many a;
 a.push_back(2);
 a.push_back(string("test"));

 for(unsigned int i=0;i<a.size();++i)
 {
  cout<<a[i].type().name()<<endl;
  try
  {
   int result = any_cast<int>(a[i]);
   cout<<result<<endl;
  }
  catch(boost::bad_any_cast & ex)
  {
   cout<<"cast error:"<<ex.what()<<endl;
  }
 }
}


2.boost::array

boost::array仅仅是对数组一层薄薄的封装,提供跟各种算法配合的iterator,使用方法很简单
注意:可以使用{}来初始化array,因为array所有的成员变量都是public的

 

#include <boost/array.hpp>
void test_array()
{
 array<int,10> ai = {1,2,3};

 for(size_t i=0;i<ai.size();++i)
 {
  cout<<ai[i]<<endl;
 }
}


3.boost::lexical_cast
lexical_cast用于将字符串转换成各种数字类型(int,float,short etc.)

 

#include <boost/lexical_cast.hpp>
void test_lexical_cast()
{
 int i = boost::lexical_cast<int>("123");
 cout << i << endl;
}


4.boost::format
boost::format是用于替代c里面的sprintf,优点是类型安全,不会因为类型和参数不匹配而导致程序崩溃了
而且还可以重复使用参数

 

#include <boost/format.hpp>
void test_format()
{
 cout << boost::format("writing %1%,  x=%2% : %3%-th try") % "toto" % 40.23 % 50 <<endl;

 format f("a=%1%,b=%2%,c=%3%,a=%1%");
 f % "string" % 2 % 10.0;

 cout << f.str() << endl;
}


5.boost::tokenizer
boost::tokenizer是用于切割字符串的,类似于Java里面的StringTokenizer。

 

#include <boost/tokenizer.hpp>
void test_tokenizer()
{
 string s("This is  , a ,test!");
 boost::tokenizer<> tok(s);
 for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
       cout << *beg << "/n";
 }
}

 

6.boost::thread
boost::thread是为了提供跨平台的thread机制。利用boost::function来完成委托。

 

#include <boost/thread.hpp>
void mythread()
{
 cout<<"hello,thread!"<<endl;
}

void test_thread()
{
 boost::function< void () > f(mythread);
 boost::thread t(f);
 t.join();
 cout<<"thread is over!"<<endl;
}


7.boost::serialization
boost::serialization提供object的序列化功能。而且提供好几种序列化的格式,比如text,binary,xml

 

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
void test_serialization()
{
 boost::archive::text_oarchive to(cout , boost::archive::no_header);
 int i = 10;
 string s = "This is a test/n";
 to & i;
 to & s;

 ofstream f("test.xml");
 boost::archive::xml_oarchive xo(f);
 xo & BOOST_SERIALIZATION_NVP(i) & BOOST_SERIALIZATION_NVP(s);

 boost::archive::text_iarchive ti(cin , boost::archive::no_header);
 ti & i & s;
 cout <<"i="<< i << endl;
 cout <<"s="<< s << endl;
}

 

8.boost::function
boost::function就是所谓的泛函数,能够对普通函数指针,成员函数指针,functor进行委托,达到迟调用的效果

 

#include <boost/function.hpp>
int foo(int x,int y)
{
 cout<< "(foo invoking)x = "<<x << " y = "<< y <<endl;
 return x+y;
}

struct test
{
 int foo(int x,int y)
 {
  cout<< "(test::foo invoking)x = "<<x << " y = "<< y <<endl;
  return x+y;
 }
};

void test_function()
{
 boost::function<int (int,int)> f;
 f = foo;
 cout << "f(2,3)="<<f(2,3)<<endl;

 test x;
 /**//*f = std::bind1st(
      std::mem_fun(&test::foo), &x);*/
 boost::function<int (test*,int,int)> f2;
 f2 = &test::foo;
 
 cout << "f2(5,3)="<<f2(&x,5,3)<<endl;
}


9.boost::shared_ptr
boost::shared_ptr就是智能指针的实现,不象std::auto_ptr,它是可以stl的容器一起使用的,非常的方便

#include <boost/shared_ptr.hpp>
class Shared
{
public:
 Shared()
 {
  cout << "ctor() called"<<endl;
 }
 Shared(const Shared & other)
 {
  cout << "copy ctor() called"<<endl;
 }
 ~Shared()
 {
  cout << "dtor() called"<<endl;
 }
 Shared & operator = (const Shared & other)
 {
  cout << "operator =  called"<<endl;
 }
};

void test_shared_ptr()
{
 typedef boost::shared_ptr<Shared> SharedSP;
 typedef vector<SharedSP> VShared;
 VShared v;
 v.push_back(SharedSP(new Shared()));
 v.push_back(SharedSP(new Shared()));
}

### Boost常用组件使用方法 #### 1. 容器类组件 Boost库中的容器组件扩展了标准模板库(STL),提供了更多种类的容器来满足不同的需求。 - **`boost::container::flat_map`**: 提供了一种基于向量实现的地图(map)结构,对于频繁查找操作效率较高。相比于红黑树实现的标准map, flat_map在某些场景下性能更优[^1]。 ```cpp #include <boost/container/flat_map.hpp> int main() { boost::container::flat_map<int, std::string> map; map.insert({1, "one"}); } ``` #### 2. 算法工具 除了增强型的数据结构外,Boost还引入了一系列实用算法函数。 - **`boost::algorithm::to_upper_copy` 和 `boost::algorithm::to_lower_copy`**: 可用于字符串大小写的转换处理,在不需要改变原字符串的情况下创建新的大写或小写字母副本[^3]。 ```cpp #include <boost/algorithm/string.hpp> std::string str = "Hello"; auto upperStr = boost::algorithm::to_upper_copy(str); // upperStr now contains "HELLO" ``` #### 3. 文件系统操作支持 文件系统的管理也是编程过程中不可或缺的一部分,通过`boost::filesystem`, 开发者能够轻松完成路径解析、目录遍历以及文件属性查询等功能。 ```cpp #include <boost/filesystem.hpp> namespace fs = boost::filesystem; if (fs::exists("example.txt")) { // check file existence auto size = fs::file_size("example.txt"); std::cout << "File exists and its size is " << size << "\n"; } else { std::cerr << "File does not exist\n"; } ``` #### 4. 正则表达式匹配 正则表达式的强大之处在于模式匹配和文本替换等方面的应用,而Boost.Regex则是C++领域内最优秀的正则表达式解决方案之一[^2]。 ```cpp #include <boost/xpressive/xpressive.hpp> using namespace boost::xpressive; sregex re = sregex::compile("\\d+"); smatch what; if(regex_search("abc123", what, re)) { std::cout << "Found number: " << what.str() << '\n'; } ``` #### 5. 时间日期处理 时间戳计算、日历运算等任务可以通过`boost::posix_time`得到简化,使得复杂的时间逻辑变得直观易懂。 ```cpp #include <boost/date_time/posix_time/posix_time.hpp> boost::posix_time::ptime t(boost::gregorian::date(2023, 8, 9)); t += boost::posix_time::hours(2); // add two hours to the time point ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值