Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Using STL vector to build a dynamic array

Posted on 2004-11-06
8
Medium Priority
?
1,307 Views
Last Modified: 2013-12-14
I am using the following header file for my project (its MFC...sigh!) (see below).

I have read that its possible to create a vector that acts almost identically to an array, but has the ability to be dynamically increased (which is just what I need).  I hope to be able to replace my static char* array and make this a CString 2 Dimensional vector that I can use the equality ("=") to pass variables.

ie.
CString tempstring =  "Hold Your Horses";
vector<MENUARRAY>;
MENUARRAY[a][b] = tempstring;
etc...

I've tried to instantiate the vector in a number of ways and am unable to figure out the syntax.  Does anyone have any idea how I would define a vector that is [19][17] and copy my current static array in to it?

Thank You!!!

    #ifndef MATRIX_H
    #define MATRIX_H

    #include <vector>  //STL-klasse
    #include <assert.h> //erstatter assert.h

    using std::vector;

    //-------------- class row for Matrix: -------------------

    template <class T>
    class row
    {
    public:            
     //klassen indeholder netop én vector = 1 række i Matrix:
     vector<T> aRow;
    };


    //-------------------- class Matrix --------------------------------
    template <class T>
    class Matrix
    {
    public:
     Matrix  (size_t Rows=0, size_t Cols=0);
     Matrix  (size_t Rows, size_t Cols, const T& Value);  
     Matrix  (const Matrix<T>& source);       //copy-constructor
     virtual ~Matrix() {};

     void Init(const T& Value);

     vector<T>& operator[] (size_t index);       //LValue indexering
     const vector<T>& operator[] (size_t index) const; //RValue indexering
     const T& GetAt (size_t Row, size_t Col) const;
     void  SetAt (size_t Row, size_t Col, const T& Value);

     Matrix<T>& operator= (const Matrix<T>& m); //assignment

     virtual void Resize(size_t Rows, size_t Cols);  
     virtual void Resize(size_t Rows, size_t Cols, const T& Value);  

     //inspektører:
     size_t NoOfRows () const;
     size_t NoOfCols () const;

    protected:

     vector< row<T> > rows;
    }; //end of class Matrix

 


   
   template <class T>
   Matrix<T>::Matrix (size_t Rows, size_t Cols)
                      : rows(Rows)
   {
     for (size_t i = 0; i < Rows; i++)
           rows[i].aRow.resize(Cols);
   }
 
   template <class T>
   Matrix<T>::Matrix  (size_t Rows, size_t Cols, const T& Value)
          : rows(Rows)
   {
         for (size_t i = 0; i < Rows; i++)
           rows[i].aRow.resize(Cols, Value);
   }

   template <class T>
   Matrix<T>::Matrix  (const Matrix<T>& source)
          : rows(source.NoOfRows() )
   {
        for (size_t i = 0; i < source.NoOfRows(); i++)
        {
          rows[i].aRow = source.rows[i].aRow;   //vector assignment
        }
   }
   
   template <class T>
   void Matrix<T>::Init  (const T& Value)
   {
     size_t i, j;
     for (i=0; i < NoOfRows(); ++i)
       for (j=0; j < NoOfCols(); ++j)
         rows[i].aRow[j] = Value;
   }

   template <class T>
   vector<T>& Matrix<T>::operator[] (size_t index)  //LValue
   {
     assert (0 <= index && index < NoOfRows());
     return rows[index].aRow;
     //aRow er en vector<T>
     //Ved indexering med [i][j] på en matrix, vil [i]
     //returnere vector<T> i den i'te række.
     //På denne bruges [j], således at det j'te element i den i'te række returneres.
     //Og det er netop element [i][j] i matrix'en!
   }

   template <class T>
   const vector<T>& Matrix<T>::operator[] (size_t index) const //RValue
   {
     assert (index < NoOfRows());
     return rows[index].aRow;
   }

   template <class T>
   const T& Matrix<T>::GetAt (size_t Row, size_t Col) const
   {
     return rows[Row].aRow[Col];
   }

   template <class T>
   void Matrix<T>::SetAt (size_t Row, size_t Col, const T& Value)
   {
     rows[Row].aRow[Col] = Value;
   }
   
   template <class T>
   Matrix<T>& Matrix<T>::operator= (const Matrix<T>& m)
   {
     if (this != &m) //check for selv-assignment
     {
       rows.resize(m.NoOfRows()); //frigiv eller alloker memory

       //kopier rækkerne fra m, en række ad gangen:
          for (size_t i = 0; i < m.NoOfRows(); ++i)
         rows[i].aRow = m.rows[i].aRow; //vector assignment
     }
     return *this;
   }
   
   template <class T>
   void Matrix<T>::Resize(size_t Rows, size_t Cols)
   {
     rows.resize(Rows);
     for (size_t i=0; i < Rows; ++i)
       rows[i].aRow.resize(Cols);
   }

   template <class T>
   void Matrix<T>::Resize(size_t Rows, size_t Cols, const T& Value)  
   {
     rows.resize(Rows);
     for (size_t i=0; i < Rows; ++i)
       rows[i].aRow.resize(Cols, Value);
   }

   template <class T>
   size_t Matrix<T>::NoOfRows () const
   {
     return rows.size();
   }

   template <class T>
   size_t Matrix<T>::NoOfCols () const
   {
     return rows[0].aRow.size();
   }

  #endif
0
Comment
Question by:vivekpara
8 Comments
 
LVL 1

Expert Comment

by:gckcmc
ID: 12515803
i didn't pour through your code, as it seemed like a straight forward response.  you could use a vector of strings?  if the number of strings is the variable, then this is straightforward...if you don't want to use the string class, then you could use a vector of vectors...likely you'll need to encapsulate this into something that you could then write your own equivalence operator....is this what you're after?
0
 
LVL 15

Expert Comment

by:efn
ID: 12516024
There is no such thing as a two-dimensional vector.  You could have a vector of CStrings, or you could have a vector of vectors of CStrings, which would be somewhat like a two-dimensional array with flexible sizes.  I can't tell from your question what you are trying to do.  Maybe it would help if you showed us the static char* array you want to replace.
0
 
LVL 9

Expert Comment

by:Hamed Zaghaghi
ID: 12516116
you can use vector like this:

first:
//include

#include <vector>

using namespace std;

second:
//decleration

vector< int > v;

third:
//add to vector

v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);

4th:
//give information

int t = v[0];

good luck;


0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 30

Expert Comment

by:Axter
ID: 12517493
Check out the class in the following link:

http://code.axter.com/dynamic_2d_array.h

With the above class you can create a two dimensional array of CString using the following method:

dynamic_2d_array<CString> myarray(rowsize, colsize);
0
 
LVL 30

Expert Comment

by:Axter
ID: 12517509
To create a 2 dimensional vector array, you can use the following method:

      int rowsize = 3;
      int colsize = 5;
      vector<vector<CString> > myarray(rowsize, vector<CString>(colsize));

      myarray[0][0] = "hello";

0
 
LVL 30

Expert Comment

by:Axter
ID: 12517561
Here's an example with a little more code:

void MyFunction()
{
      int rowsize = 19;
      int colsize = 17;
      vector<vector<CString> > myarray(rowsize, vector<CString>(colsize));

      int r;
      for(r = 0;r < rowsize;++r)
      {
            for(int c = 0;c < colsize;++c)
            {
                  myarray[r][c].Format("row-%i col-%i", r, c);
            }
      }

      for(r = 0;r < rowsize;++r)
      {
            for(int c = 0;c < colsize;++c)
            {
                  cout << (LPCTSTR)myarray[r][c] << endl;
            }
      }

}

0
 
LVL 30

Accepted Solution

by:
Axter earned 2000 total points
ID: 12517589
Here's an example of how to take a static 2D array, and push it on to a vector 2d array.

void MyFunction()
{
      const int rowsize = 19;
      const int colsize = 17;

      CString my_static_array[rowsize][colsize];

      int r;
      for(r = 0;r < rowsize;++r)
      {
            for(int c = 0;c < colsize;++c)
            {
                  my_static_array[r][c].Format("row-%i col-%i", r, c);
            }
      }

      vector<vector<CString> > myarray;
      for(r = 0;r < rowsize;++r)
      {
            myarray.push_back(vector<CString>(&my_static_array[r][0], &my_static_array[r][colsize]));
      }

      for(r = 0;r < rowsize;++r)
      {
            for(int c = 0;c < colsize;++c)
            {
                  cout << (LPCTSTR)myarray[r][c] << endl;
            }
      }

}
0
 
LVL 2

Author Comment

by:vivekpara
ID: 12519393
Elegant code, Axter.  I have to admit that I still don't get STL completely, but I'm working on it.  How the templates are formed from the code you gave still puzzles me.

That fixes my problem.  Thanks to all for your help...sorry I didn't write back sooner...I was actually trying to have some FUN this weekend.  Sigh!

=)
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question