为什么要用boost::array

为什么要用boost::array


1、boost::array 与 std::vector
( From Chapter 2. Boost.Array)
As replacement for ordinary arrays, the STL provides class std::vector. However, std::vector<>

provides the semantics of dynamic arrays. Thus, it manages data to be able to change the number

of elements. This results in some overhead in case only arrays with static size are needed.

2、便于使用stl中的算法

3、越界检查
   尽管抛出assert错误,但总比没有强

4、整体操作数据很方便
  boost::array::assign(...)


-----------------------------------------------------------
eg:


#include <iostream>
#include <algorithm>
#include <string>
#include <boost/array.hpp>

template<typename T>
void PrintValue(T value)
{
 std::cout<<value<<std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
 //---------------------------------
 //int
 
 boost::array<int, 10> arrInt = {0,1,2}; //未赋值的初试化为0
 std::for_each(arrInt.begin(),arrInt.end(),PrintValue<int>);
 
 //所有的值都赋为20
 arrInt.assign(20);
 std::for_each(arrInt.begin(),arrInt.end(),PrintValue<int>);

 //--------------------------------------
 //string
 boost::array<std::string, 5> arrStr; //默认为""
 arrStr.assign("NULL");
 std::for_each(arrStr.begin(),arrStr.end(),PrintValue<std::string>);

 //越界检查
 //std::string strErr = arrStr[5]; //发出assert

 //比较
 boost::array<std::string, 5> arrStr2;
 arrStr2.assign("MULL");
 if(arrStr > arrStr2)
  std::cout << "arrStr > arrStr2" <<std::endl;
 
 if(arrStr != arrStr2)
  std::cout << "arrStr != arrStr2" <<std::endl;

 //boost::array<std::string, 6> arrStr3;
 //arrStr3.assign("NULL");
 //if(arrStr != arrStr3)   //无法比较,类型不同5 != 6
 // std::cout << "arrStr != arrStr3" <<std::endl;

 return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值