Vector storage in C++

前端 未结 5 539
轮回少年
轮回少年 2021-02-05 01:08

I wish to store a large vector of d-dimensional points (d fixed and small: <10).

If I define a Point as vector, I think a v

5条回答
  •  情深已故
    2021-02-05 01:21

    As the dimension is fixed, I'd suggest you to go with a template which uses the dimension as a template param. Something like this:

    template  class ndpoint 
    {
    public:
      using elem_t=
        typename std::enable_if::value, R>::type;
    
      static constexpr std::size_t DIM=N;
    
      ndpoint() = default;
    
      // e.g. for copying from a tuple
      template  ndpoint(coordt... x) : elems_ {static_cast(x)...} {
      }
      ndpoint(const ndpoint& other) : elems_() {
        *this=other;
      }
    
      template  ndpoint(const PointType& other) : elems_() {
        *this = other;
      }
    
      ndpoint& operator=(const ndpoint& other) {
        for(size_t i=0; ielems_[i]=other.elems_[i];
        }
        return *this;
      }
    
      // this will allow you to assign from any source which defines the
      // [](size_t i) operator
      template  ndpoint& operator=(const PointT& other) {
        for(size_t i=0; ielems_[i]=static_cast(other[i]);
        }
      }
    
      const R& operator[](std::size_t i) const { return this->elems_[i]; }
    
      R& operator[](std::size_t i) { return this->elems_[i]; }
    
    private:
      R elems_[N];
    };
    

    Then use a std::vector> for a collection of points for best performance.

提交回复
热议问题