初始化boost数组/ multi_array

时间:2009-12-28 20:28:32

标签: c++ arrays boost initialization

我已使用

定义boost::(multi_)array
typedef boost::multi_array<unsigned int, 1>  uint_1d_vec_t;
typedef boost::multi_array<unsigned int, 2>  uint_2d_vec_t;

uint_1d_vec_t    foo( boost::extents[ num_elements   ]          );
uint_2d_vec_t    boo( boost::extents[ num_elements/2 ][ kappa ] );

num_elements/2是一个整数,kappa是一个整数,但只包含整数(例如79)。

如果仅在运行时知道它们中的元素数量,我如何将fooboo初始化为0

4 个答案:

答案 0 :(得分:2)

更改行

  std::fill( boo.begin()->begin() , boo.end()->end() , 0);

  std::fill( boo.origin(), boo.origin() + boo.size(), 0 );

解决了我的问题

答案 1 :(得分:-1)

uint_1d_vec_t    foo( boost::extents[ static_cast< uint_1d_vec_t::index >( num_elements   ) ]          );
uint_2d_vec_t    boo( boost::extents[ static_cast< uint_2d_vec_t::index >( num_elements/2 ) ][ static_cast< uint_2d_vec_t::index >( kappa ) ] );

答案 2 :(得分:-1)

您可能还希望使用calloc,然后使用boost :: multi_array_ref包装返回的内存。

答案 3 :(得分:-3)

我用过

std::fill( foo.begin() , foo.end()    , 0);

解决我的问题(不知道它是否比boost :: assign更好,因为我无法应用它)。

boo我还有问题,因为     std :: fill(boo.begin() - &gt; begin(),boo.end() - &gt; end(),0); 传递编译,但是一旦我运行我的程序,我得到以下错误:

  

/usr/include/boost/multi_array/base.hpp:178:引用boost :: detail :: multi_array :: value_accessor_one :: access(boost :: type,boost :: multi_array_types :: index,TPtr,const boost :: multi_array_types :: size_type *,const boost :: multi_array_types :: index *,const boost :: multi_array_types :: index *)const [with Reference = unsigned int&amp;,TPtr = unsigned int *,T = unsigned int]:Assertion `size_type(idx - index_bases [0])&lt;范围[0]'failed.Blockquote

这是一个简短的代码:

#include <iomanip>
#include "boost/multi_array.hpp"
#include <iostream>

namespace vec {
   typedef boost::multi_array<unsigned int, 1>  uint_1d_vec_t;
   typedef boost::multi_array<unsigned int, 2>  uint_2d_vec_t;
   typedef uint_1d_vec_t::index                 index_1d_t;
   typedef uint_2d_vec_t::index                 index_2d_t;
}

using namespace std;

int main( ) { 

   unsigned int num_elements, num_bits, max_runs, m;
   num_bits = 12;
   max_runs = 5000;
   m        = 2;

   num_elements = ( 1 << num_bits );

   double kappa = 79;

   vec::uint_1d_vec_t    foo( boost::extents[ static_cast< vec::index_1d_t >(num_elements) ]                                          );
   vec::uint_2d_vec_t    boo( boost::extents[ static_cast< vec::index_2d_t >(num_elements) ][ static_cast< vec::index_2d_t >(kappa) ] );

   std::fill( foo.begin()          , foo.end()        , 0);
   std::fill( boo.begin()->begin() , boo.end()->end() , 0);

   std::cout << "Done" << std::endl;

   return EXIT_SUCCESS;
}
相关问题