大家都希望可以像操作STL容器一样的去操作数组,C++可没有提供这个东西,有时候你会选择使用vector来替代,不过这毕竟不是个好的办法,毕竟vector模拟动态数组比较稳妥,而用它去替代一个普通的数组,开销毕竟太大了。而恰好,boost::array就为你提供了这个功能。boost::array的定义如下(简化):
template
<
class
T, std::size_t N
>
class
array
{
public
: T elems[N];
//
fixed-size array of elements of type T
public
:
//
type definitions
typedef T value_type;
typedef T
*
iterator;
typedef
const
T
*
const_iterator;
typedef T
&
reference;
typedef
const
T
&
const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
//
iterator support
iterator begin() {
return
elems; }
const_iterator begin()
const
{
return
elems; }
iterator end() {
return
elems
+
N; }
const_iterator end()
const
{
return
elems
+
N; }
//
operator[]
reference
operator
[](size_type i) ;
const_reference
operator
[](size_type i)
const
;
//
at() with range check
reference at(size_type i) ;
const_reference at(size_type i)
const
;
//
front() and back()
reference front() ;
const_reference front()
const
;
reference back() ;
const_reference back()
const
;
//
size is constant
static
size_type size() {
return
N; }
static
bool
empty() {
return
false
; }
static
size_type max_size() {
return
N; }
enum
{ static_size
=
N };
//
swap (note: linear complexity)
void
swap (array
<
T,N
>&
y) ;
}
显而易见,其实它只是将数组简单的包装,并附加了迭代器而已,你可以把它当成是普通的数组来使用,也可以进行STL的算法操作,是不是很方便?当然它也是有弊端的,当你想要创建一个未知个数的数组时,你就无能为力了:
int
[] arr
=
{
1
,
2
,
3
};
//
boost::array<int,N> arr = {1,2,3}
//
error!
当然,有这种需要的时候你还是要用普通的数组,不过在其他的时候呢?
那么,我们来比较一下他们的运行效率。
我们分别创建boost::array,std::vector,普通数组,并对他们进行赋值。
#define
_size 10000
#define
_recount 10000
//
计算时间用
DWORD start, finish;
double
duration;
首先是boost::array
boost::array
<
int
,_size
>
a_int;
start
=
timeGetTime();
int
i
=
0
;
for
(i
=
0
;i
<
_recount;i
++
)
{
for
(
int
j
=
0
;j
<
_size;j
++
)
{
a_int[j]
=
j;
}
}
finish
=
timeGetTime();
duration
=
(
double
)(finish
-
start)
/
CLOCKS_PER_SEC;
然后是std::vector
vector
<
int
>
v_int;
v_int.resize(_size);
start
=
timeGetTime();
for
(i
=
0
;i
<
_recount;i
++
)
{
for
(
int
j
=
0
;j
<
_size;j
++
)
{
v_int[j]
=
j;
}
}
finish
=
timeGetTime();
duration
=
(
double
)(finish
-
start)
/
CLOCKS_PER_SEC;
最后是普通数组
int
_int[_size];
start
=
timeGetTime();
for
(i
=
0
;i
<
_recount;i
++
)
{
for
(
int
j
=
0
;j
<
_size;j
++
)
{
_int[j]
=
j;
}
}
finish
=
timeGetTime();duration
=
(
double
)(finish
-
start)
/
CLOCKS_PER_SEC;
得出运行时间:
Boost::array :
3.296
std::vector :
10.453
普通数组 :
0.296
Oh my god ! 相差这么多? 恩,的确相差了这么多!因为我们是使用的int类型作为操作数,那么当我们使用自定义的class的时候时间如下:
boost::array :
12.656
std::vector :
18.656
普通数组 :
9.609
这个时候,我们可以看出,普通的数组比boost::array快了1/4,而比std::vector快了1/2。