STL General: How to declare and use two-dimensional arrays?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 1 of 1

Thread: STL General: How to declare and use two-dimensional arrays?

Threaded View

  1. #1
    Join Date
    Aug 2002

    STL General: How to declare and use two-dimensional arrays ?

    Q: How can I define a dynamic two-dimensional array?

    A: The basic idea is to use a 'vector<vector<T> >'. Use containment to write a template class that offers the desired functionality. Following skeleton code shows how to implement and use such a class:

    #include <vector>
    template <typename T>
    class dynamic_array
      dynamic_array(int rows, int cols)
        for(int i=0; i<rows; ++i)
      // other ctors ....
      inline std::vector<T> & operator[](int i) { return data_[i]; }
      inline const std::vector<T> & operator[] (int i) const { return data_[i]; }
      // other accessors, like at() ...
      void resize(int rows, int cols)
        for(int i = 0; i < rows; ++i)
      // other member functions, like reserve()....
      std::vector<std::vector<T> > data_;  
    int main()
      dynamic_array<int> a(3, 3);
      a[1][1] = 2;
      int x = a[1][1];
      return 0;
    A different approach, not using the STL 'vector' class, is shown in the following FAQ...

    FAQ contributed by: [Gabriel Fleseriu] [Axter]

    Last edited by Andreas Masur; July 24th, 2005 at 01:55 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

This is a survey!

HTML5 Development Center