论坛首页 编程语言技术论坛

boost笔记4(boost::multi_array)

浏览 2511 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-07-30  
C++

boost::multi_array
一言以概之,boost::multi_array就是N维数组。boost::multi_array可以看作STL容器类的扩展,可以和STL相关算法一起工作。
在STL中,N维数组可以通过std::vector<std::vector<...> >类似的方法来模拟,相比而言,boost::multi_array更高效,更直观。

例程1:

#include <cassert>
#include "boost/multi_array.hpp"
#include "boost/cstdlib.hpp"

int main () {
  // Create a 3D array that is 3 x 4 x 2
  typedef boost::multi_array<double, 3> array;
  array A(boost::extents[3][4][2]);
  // Assign a value to an element in the array
  A[0][0][0] = 3.14;
  assert(A[0][0][0] == 3.14);
  return boost::exit_success;
}

 

例程2:

 

 

#include <cassert>
#include "boost/multi_array.hpp"
#include "boost/array.hpp"
#include "boost/cstdlib.hpp"

int main () {
  // Create a 3D array that is 3 x 4 x 2
  boost::array<int, 3> shape = {{ 3, 4, 2 }};
  boost::multi_array<double, 3> A(shape);
  // Assign a value to an element in the array
  A[0][0][0] = 3.14;
  assert(A[0][0][0] == 3.14);
  return boost::exit_success;
}

 

 

例程3:

 

#include <iostream>
#include "boost/multi_array.hpp"
#include "boost/array.hpp"
#include "boost/cstdlib.hpp"

template <typename Array>
void print(std::ostream& os, const Array& A) {
  typename Array::const_iterator i;
  os << "[";
  for (i = A.begin(); i != A.end(); ++i) {
    print(os, *i);
    if (boost::next(i) != A.end())
      os << ',';
  }
  os << "]";
}

void print(std::ostream& os, const double& x) {
  os << x;
}

int main() {
  typedef boost::multi_array<double, 2> array;
  double values[] = {
    0, 1, 2,
    3, 4, 5 
  };
  const int values_size = 6;
  array A(boost::extents[2][3]);
  A.assign(values,values + values_size);
  print(std::cout, A);
  return boost::exit_success;
}

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics