转自:
http://grantren.javaeye.com/blog/221457
boost::multi_array
一言以概之,boost::multi_array就是N维数组。boost::multi_array可以看作STL容器类的扩展,可以和STL相关算法一起工作。
在STL中,N维数组可以通过std::vector<std::vector<...> >类似的方法来模拟,相比而言,boost::multi_array更高效,更直观。
例程1:
1 #include <cassert>
2 #include "boost/multi_array.hpp"
3 #include "boost/cstdlib.hpp"
4
5 int main () {
6 // Create a 3D array that is 3 x 4 x 2
7 typedef boost::multi_array<double, 3> array;
8 array A(boost::extents[3][4][2]);
9 // Assign a value to an element in the array
10 A[0][0][0] = 3.14;
11 assert(A[0][0][0] == 3.14);
12 return boost::exit_success;
13 }
14
例程2:
1 #include <cassert>
2 #include "boost/multi_array.hpp"
3 #include "boost/array.hpp"
4 #include "boost/cstdlib.hpp"
5
6 int main () {
7 // Create a 3D array that is 3 x 4 x 2
8 boost::array<int, 3> shape = {{ 3, 4, 2 }};
9 boost::multi_array<double, 3> A(shape);
10 // Assign a value to an element in the array
11 A[0][0][0] = 3.14;
12 assert(A[0][0][0] == 3.14);
13 return boost::exit_success;
14 }
15
例程3:
1 #include <iostream>
2 #include "boost/multi_array.hpp"
3 #include "boost/array.hpp"
4 #include "boost/cstdlib.hpp"
5
6 template <typename Array>
7 void print(std::ostream& os, const Array& A) {
8 typename Array::const_iterator i;
9 os << "[";
10 for (i = A.begin(); i != A.end(); ++i) {
11 print(os, *i);
12 if (boost::next(i) != A.end())
13 os << ',';
14 }
15 os << "]";
16 }
17
18 void print(std::ostream& os, const double& x) {
19 os << x;
20 }
21
22 int main() {
23 typedef boost::multi_array<double, 2> array;
24 double values[] = {
25 0, 1, 2,
26 3, 4, 5
27 };
28 const int values_size = 6;
29 array A(boost::extents[2][3]);
30 A.assign(values,values + values_size);
31 print(std::cout, A);
32 return boost::exit_success;
33 }
34