Define your own type (trivial), give it an iterator and const_interator (trivial), and BOOST_FOREACH will work with it.
glowcoder
2010-07-16 15:40:03
Define your own type (trivial), give it an iterator and const_interator (trivial), and BOOST_FOREACH will work with it.
hello.
I do the following (array_type is container/iterator range concept)
ublas::matrix<douple> A;
foreach (double & element, A.data()) {
however, this will not work for slices. your best solution is to write iterator of them .
here is an example of using multi array to provide storage of custom class. Perhaps you could do the same?:
template<size_t N, typename T>
struct tensor_array : boost::multi_array_ref<T,N> {
typedef boost::multi_array_ref<T,N> base_type;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
tensor_array() : base_type(NULL, extents())
{
// std::cout << "create" << std::endl;
}
template<class A>
tensor_array(const A &dims)
: base_type(NULL, extents())
{
//std::cout << "create" << std::endl;
resize(dims);
}
template<typename U>
void resize(const U (&dims)[N]) {
boost::array<U,N> dims_;
std::copy(dims, dims + N, dims_.begin());
resize(dims_);
}
template<typename U>
void resize(const boost::array<U,N> &dims) {
size_t size = 1;
boost::array<size_t,N> shape;
for (size_t i = 0; i < N; ++i) {
size *= dims[i];
shape[N-(i+1)] = dims[i];
}
data_.clear();
data_.resize(size, 0);
// update base_type parent
set_base_ptr(&data_[0]);
this->num_elements_ = size;
reshape(shape);
}
size_t size() const { return data_.size(); }
size_t size(size_t i) const { return this->shape()[N-(i+1)]; }
tensor_array& fill(const T &value) {
std::fill(data_.begin(), data_.end(), value);
return *this;
}
private:
typedef boost::detail::multi_array::extent_gen<N> extents;
std::vector<T> data_;
};