What is the most efficient way to initialize a 3D vector?

后端 未结 5 1353
长情又很酷
长情又很酷 2021-02-03 11:23

I have a 3D string vector in C++:

vector>> some_vector

That I am trying is to find a fast method to all

5条回答
  •  无人共我
    2021-02-03 11:38

    May I know what cause such difference?

    The first version constructs a 2-d vector by copying a 1-d vector, and then constructs the 3-d vector by copying that. This might be slower than resizing the vectors without copying. However, I'd hope that the difference would be negligible if you're building with optimisation.

    And is there better way to allocate memory for a 3D vector?

    It might be better to use a single contiguous array, wrapped in a class that provides multi-dimensional accessors. This would make allocation much simpler, and would also avoid some pointer dereferencing when accessing elements (at the cost of a bit of arithmetic). Something like this:

    template 
    class vector3d {
    public:
        vector3d(size_t d1=0, size_t d2=0, size_t d3=0, T const & t=T()) :
            d1(d1), d2(d2), d3(d3), data(d1*d2*d3, t)
        {}
    
        T & operator()(size_t i, size_t j, size_t k) {
            return data[i*d2*d3 + j*d3 + k];
        }
    
        T const & operator()(size_t i, size_t j, size_t k) const {
            return data[i*d2*d3 + j*d3 + k];
        }
    
    private:
        size_t d1,d2,d3;
        std::vector data;
    };
    

提交回复
热议问题