manipulating multidimensional arrays with functions in C++

后端 未结 4 1562
南笙
南笙 2020-12-18 16:31

I am trying to modify the contents of a 2D array in C++ using a function. I haven\'t been able to find information on how to pass a 2D array to a function by reference and

4条回答
  •  盖世英雄少女心
    2020-12-18 16:57

    C++ allows you to encapsulate code structures like this into an object, for example an array has the std::vector and std::array object.

    I personally roll my own matrix containers. This way you don't have to worry about the details of how they are passed.

    A basic example of a matrix implemenation could be:

    template
    class matrix
    {
    public:                     //TYPEDEFS
        typedef                         T                                                       value_type;
    private:
        typedef                 std::vector         vect_type;
    public:
        typedef typename        vect_type::iterator             iterator;
        typedef typename        vect_type::const_iterator       const_iterator;
    
    private:            //DATAMEMBERS
        vect_type values;
        size_t x_sz, y_sz;/not const for assingment reasons
    
    public:                     //MEMBER FUNCTIONS
        matrix(const matrix&)           =default;
        matrix(matrix&&)                =default;
        matrix& operator=(const matrix&)=default;
        matrix& operator=(matrix&&)     =default;
    
        matrix(size_t x_sz_=0u, size_t y_sz_=0u, value_type t=value_type())
        : values(x_sz_*y_sz_, t)
        , x_sz(x_sz_)
        , y_sz(y_sz_)
        { }
    
        //return        symbol          const   body
        size_t          x_size()        const   { return x_sz; }
        size_t          y_size()        const   { return y_sz; }
    
        iterator        begin()                 { return values.begin();        }
        iterator        end()                   { return values.end();          }
        const_iterator  begin()         const   { return values.cbegin();       }
        const_iterator  end()           const   { return values.cend();         }
        const_iterator  cbegin()        const   { return values.cbegin();       }
        const_iterator  cend()          const   { return values.cend();         }
    
        value_type& at(size_t x, size_t y)
        {
                return values.at(y*x_sz+x);
        }
    
        const value_type& at(size_t x, size_t y) const
        {
                return values.at(y*x_sz+x);
        }
    };  //class matrix
    

    Then you simply do the following:

     void func(const mat& m)....
     :::
    
     matrix mat(3,3);
    
     //this isn't necessary as the ctor take a default value,
     // however it show you how you might iterate through the values.
     for(size_t y=0; y!=mat.y_size(); ++y)
        for(size_t x=0; x!=mat.x_size(); ++x)
            mat.at(x, y)=0; 
    
    func(mat); //as param
    

提交回复
热议问题