数组可能是C/C++程序员用得最多的了,但到现在数组有不少不如人意的地方。 比较重要的一点是在
这个STL 时代,数组不支持STL的标准算法让人郁闷。虽然许多大腕级的人物都指出用std::vector来替代数组,
但vector是动态语义,会有许多的开销,特别是当你确实只需要一个定长数组时,这些额外的开销可能让你难
以忍受。
还好,boost给这一类用户提供了他们想要的东西array,呵,有点鱼和熊掌兼得的味道呵。array已被
提交做为下一个C++标准扩展技术报告的一部分(http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1548.htm),
是一个不错的东西。
来看一个简单的例子:
#include <boost/array.hpp>
using namespace boost;
template<typename T, std::size_t N>
void printf_array(array<T, N> a)
{
array<T, N>::iterator iter;
for(iter=a.begin(); iter!=a.end(); ++iter)
{
cout << *iter << " " ;
}
cout << endl << endl ;
}
void boost_array_test()
{
const int a_len = 10;
const int b_len = 15;
array<int, a_len> a = {0};
int temp[a_len] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << "copy普通数组至boost::array :" << endl;
memcpy(a.c_array(), temp, sizeof(temp));
printf_array<int, a_len>(a);
array<int, b_len> b;
cout << "赋值 :" << endl;
b.assign(0);
printf_array<int, b_len>(b);
cout << "拷贝 :" << endl;
std::copy(a.begin(), a.end(), b.begin());
printf_array<int, b_len>(b);
cout << "随机洗牌 :" << endl;
std::random_shuffle(b.begin(), b.end());
printf_array<int, b_len>(b);
cout << "排序 :" << endl;
std::sort(b.begin(), b.end());
printf_array<int, b_len>(b);
}
结果如下
最后要注意的是boost::array完成大部分但不是所有的可逆容器的要求,原因是
1. 没有提供构造器
2. 没有常量复杂性
3. size()总是常量
4. 没有完成序列支持,除了:front() 、 back() 、operator[] 、 at()
这个STL 时代,数组不支持STL的标准算法让人郁闷。虽然许多大腕级的人物都指出用std::vector来替代数组,
但vector是动态语义,会有许多的开销,特别是当你确实只需要一个定长数组时,这些额外的开销可能让你难
以忍受。
还好,boost给这一类用户提供了他们想要的东西array,呵,有点鱼和熊掌兼得的味道呵。array已被
提交做为下一个C++标准扩展技术报告的一部分(http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1548.htm),
是一个不错的东西。
来看一个简单的例子:
#include <boost/array.hpp>
using namespace boost;
template<typename T, std::size_t N>
void printf_array(array<T, N> a)
{
array<T, N>::iterator iter;
for(iter=a.begin(); iter!=a.end(); ++iter)
{
cout << *iter << " " ;
}
cout << endl << endl ;
}
void boost_array_test()
{
const int a_len = 10;
const int b_len = 15;
array<int, a_len> a = {0};
int temp[a_len] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << "copy普通数组至boost::array :" << endl;
memcpy(a.c_array(), temp, sizeof(temp));
printf_array<int, a_len>(a);
array<int, b_len> b;
cout << "赋值 :" << endl;
b.assign(0);
printf_array<int, b_len>(b);
cout << "拷贝 :" << endl;
std::copy(a.begin(), a.end(), b.begin());
printf_array<int, b_len>(b);
cout << "随机洗牌 :" << endl;
std::random_shuffle(b.begin(), b.end());
printf_array<int, b_len>(b);
cout << "排序 :" << endl;
std::sort(b.begin(), b.end());
printf_array<int, b_len>(b);
}
结果如下
/*
copy普通数组至boost::array :
0 1 2 3 4 5 6 7 8 9
赋值 :
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
拷贝 :
0 1 2 3 4 5 6 7 8 9 0 0 0 0 0
随机洗牌 :
0 1 9 2 0 0 7 3 4 6 8 5 0 0 0
排序 :
0 0 0 0 0 0 1 2 3 4 5 6 7 8 9
*/
copy普通数组至boost::array :
0 1 2 3 4 5 6 7 8 9
赋值 :
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
拷贝 :
0 1 2 3 4 5 6 7 8 9 0 0 0 0 0
随机洗牌 :
0 1 9 2 0 0 7 3 4 6 8 5 0 0 0
排序 :
0 0 0 0 0 0 1 2 3 4 5 6 7 8 9
*/
最后要注意的是boost::array完成大部分但不是所有的可逆容器的要求,原因是
1. 没有提供构造器
2. 没有常量复杂性
3. size()总是常量
4. 没有完成序列支持,除了:front() 、 back() 、operator[] 、 at()