A proper way to create a matrix in c++

后端 未结 10 2355
無奈伤痛
無奈伤痛 2020-11-27 05:33

I want to create an adjacency matrix for a graph. Since I read it is not safe to use arrays of the form matrix[x][y] because they don\'t check for range, I deci

10条回答
  •  孤城傲影
    2020-11-27 06:24

    If you want 'C' array performance, but with added safety and STL-like semantics (iterators, begin() & end() etc), use boost::array.

    Basically it's a templated wrapper for 'C'-arrays with some NDEBUG-disable-able range checking asserts (and also some std::range_error exception-throwing accessors).

    I use stuff like

    boost::array,4> m;
    

    instead of

    float m[4][4];
    

    all the time and it works great (with appropriate typedefs to keep the verbosity down, anyway).


    UPDATE: Following some discussion in the comments here of the relative performance of boost::array vs boost::multi_array, I'd point out that this code, compiled with g++ -O3 -DNDEBUG on Debian/Lenny amd64 on a Q9450 with 1333MHz DDR3 RAM takes 3.3s for boost::multi_array vs 0.6s for boost::array.

    #include 
    #include 
    #include "boost/array.hpp"
    #include "boost/multi_array.hpp"
    
    using namespace boost;
    
    enum {N=1024};
    
    typedef multi_array M;
    typedef array,N>,N> C;
    
    // Forward declare to avoid being optimised away
    static void clear(M& m);
    static void clear(C& c);
    
    int main(int,char**)
    {
      const clock_t t0=clock();
    
      {
        M m(extents[N][N][N]);
        clear(m);
      }
    
      const clock_t t1=clock();
    
      {
        std::auto_ptr c(new C);
        clear(*c);
      }
    
      const clock_t t2=clock();
    
      std::cout 
        << "multi_array: " << (t1-t0)/static_cast(CLOCKS_PER_SEC) << "s\n"
        << "array      : " << (t2-t1)/static_cast(CLOCKS_PER_SEC) << "s\n";
    
      return 0;
    }
    
    void clear(M& m)
    {
      for (M::index i=0;i

提交回复
热议问题