【问题标题】:Boost Multiarray Dimensions提升多阵列维度
【发布时间】:2012-03-08 01:06:57
【问题描述】:

我有一个 Boost 多数组,它的维度是在运行时根据用户的输入设置的。

我现在想通过 x,y,z 组件迭代该数组。

如果这是一个 std::vector,我会使用:

for(int i=0;i<v.size();i++){

或者也许是某种迭代器。

如何获取多数组维度的数值?

如何迭代多数组?

谢谢!

【问题讨论】:

    标签: c++ boost iterator boost-multi-array


    【解决方案1】:

    您可以使用shape() 来减少复杂度:

    #include <iostream>
    #include <string>
    #include <boost/multi_array.hpp>
    
    int main() {
        boost::multi_array<std::string, 2> a(boost::extents[3][5]);
        for(size_t x = 0; x < a.shape()[0]; x++) {
            for(size_t y = 0; y < a.shape()[1]; y++) {
                std::ostringstream sstr;
                sstr << "[" << x << ", " << y << "]";
                a[x][y] = sstr.str();
            }
        }
        for(size_t x = 0; x < a.shape()[0]; x++) {
            for(size_t y = 0; y < a.shape()[1]; y++) {
                std::cout << a[x][y] << "\n";
            }
        }
        return 0;
    }
    

    (查看实际操作on coliru

    【讨论】:

      【解决方案2】:
      #include "boost/multi_array.hpp"
      #include <iostream>
      #include <algorithm>
      #include <iterator>
      
      int main () {
          typedef boost::multi_array_types::index_range range;
          typedef boost::multi_array<char, 2> Array2d;
          Array2d a(boost::extents[8][24]);
      
          //to view the two-dimensional array as a one-dimensional one can use multi_array_ref?
          boost::multi_array_ref<char, 1> a_ref(a.data(), boost::extents[a.num_elements()]);
          std::fill(a_ref.begin(), a_ref.end(), '-');
      
          //to apply algorithm to one row or column, can use array_view
          //especially useful for traversing it vertically?
          //e.g:
          Array2d::array_view<1>::type views[4] = {
              a[boost::indices[range()][0]], //left column
              a[boost::indices[range()][a[0].size() - 1]], //right column
              a[boost::indices[0][range()]], //top row
              a[boost::indices[a.size()-1][range()]] //bottom row
          };
          for (unsigned i = 0; i != sizeof(views)/sizeof(views[0]); ++i) {
              std::fill ( views[i].begin(), views[i].end(), 'X' );
          }
      
          //output
          for (unsigned i = 0; i != a.size(); ++i) {
              std::copy(a[i].begin(), a[i].end(), std::ostream_iterator<char>(std::cout, ""));
              std::cout << '\n';
          }
      }
      

      来源:http://cboard.cprogramming.com/cplusplus-programming/112584-boost-multiarray.html

      【讨论】:

      • 谢谢。这看起来很复杂,我调查了一些事情,我将尝试使用 boost uBLAS 矩阵。
      • 我曾经对 uBLAS 和共享指针有过一些“乐趣”,但不记得细节了。看看 C++11 中的元组类型怎么样?
      猜你喜欢
      • 1970-01-01
      • 2018-09-09
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多