大家都希望可以像操作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。
那麼結論就是:
1. 在使用基本類型時,如無特殊需要,使用普通數組的效率遠遠高於另外兩者。
2. 在使用class時,當boost::array帶來的代碼便利和可讀性的情況,使用boost::array所損失的效能可以忽略不計。
好吧,這不是讓你放棄std::vector,而是提供了另外一個好用的容器,並且給一個直觀的印象。
但是這是在沒有最佳化並且開了DEBUG資訊的情況下的結果,如果我們開啟最佳化並且去掉一切的調試資訊的結果如下