我的意思是typedef
一个固定大小的矢量/增强矢量的名称,然后是相应的迭代器。我能做的是(见下文)
typedef std::array<double, 3> point_3d_array;
typedef point_3d_array::iterator point_3d_iterator;
typedef point_3d_array::const_iterator point_3d_const_iterator;
我的想法是稍后在我的代码中使用类似的东西
point_3d_array p;
for ( point_3d_const_iterator it = p.begin() ; it != p.end() ; it++ ) {
my code
}
问题1:这是否可行
std::vector<double>
boost::numeric::ublas::vector<double>
?如果不可能:
typedef
迭代器?截至目前,由于我找不到办法,我定义了自己的类(见下文)。但这带来了(至少)必须重新定义我自己的begin
,end
和迭代器(例如,this)的负担。我的意思是避免这种情况。
问题4:我在operator+=
的定义中汇总了两个替代线(见下文)。其中一个不起作用。问题是什么?
typedef std::array<double, 3> point_3d_array;
typedef point_3d_array::iterator point_3d_iterator;
typedef point_3d_array::const_iterator point_3d_const_iterator;
class point_3d {
public:
/*
* Default constructor
*/
point_3d() : _point_3d({ 0, 0, 0 }) { };
/*
* Initialization constructor
* Is copy constructor automatically generated?
*/
point_3d(const double x1, const double x2, const double x3) : _point_3d({x1, x2, x3}) {};
/*
* Iterator members
*/
point_3d_iterator begin() { return _point_3d.begin(); }
point_3d_iterator end() { return _point_3d.end(); }
point_3d_const_iterator begin() const { return _point_3d.begin(); }
point_3d_const_iterator end() const { return _point_3d.end(); }
/*
* Array subscript operators
*/
double & operator[](size_t i) {
return this->_point_3d[ i ];
}
const double & operator[](size_t i) const {
return this->_point_3d[ i ];
}
/*
* Basic operation members
*/
point_3d & operator+=(const point_3d &rhs) {
for ( size_t i = 0 ; i < this->_point_3d.size() ; i++ ) {
//this[ i ] += rhs[ i ]; // Why are Array subscript operators not working in the lhs?
this->_point_3d[ i ] += rhs[ i ];
}
return *this;
}
private:
point_3d_array _point_3d;
};
std::vector
和(在撰写本文时)boost::numeric::ublas::vector
都没有设计为固定大小。没有模板参数指定容器的大小。
所以不,固定大小的typedef
对这些容器毫无意义。
如果你想约束std::vector
的大小,那么一种方法是用std::vector
编写你自己的模板类来模拟有效载荷。
boost :: numeric :: ublas有一个固定大小的存储容器和一个固定大小的向量。我不确定你是否必须使用typedef
作为迭代器类型和矢量类型。这是一个小例子,如何使用这两种类型,甚至与std::array
或std::vector
混合使用。
#include <boost/numeric/ublas/storage.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <array>
#include <numeric>
using namespace boost::numeric;
using value_t = float;
int main () {
constexpr auto N = 5ul;
auto a = ublas::bounded_array<value_t,N>{N};
auto b = ublas::fixed_vector<value_t,N>{};
auto c = std::array<value_t,N>{};
auto print = [](auto n, auto v){
std::cout << n << "= ";
std::copy(v.begin(), v.end(), std::ostream_iterator<value_t>(std::cout, " "));
std::cout << std::endl;
};
std::iota(a.begin(), a.end(), value_t(1));
std::iota(b.begin(), b.end(), value_t(1));
std::transform(a.begin(), a.end(), b.begin(), c.begin(), [](auto const& aa, auto const& bb){return aa+bb;});
auto d = 2*b + b;
print("a",a);
print("b",b);
print("c",c);
print("d",d);
return 0;
}