Lakshmi Narayanan
Lakshmi Narayanan

Reputation: 5342

2D array operations using vector

I have been using vectors only lately and found them extremely handy when compared normal array declarations. however, I have dealt with only 1D operations as following:-

      vector<int>X;
      X.push_back(value/variable);

How Do I perform similar operations for a 2D vector equivalent and dynamically update values, row by row? Please help me here and my apologies if the question is rudimentary. Also it would be really helpful if you can show me a link where all operations of vectors are provided as tutorials. I tried few sites, but they are bits all over. Please help me.

Upvotes: 0

Views: 839

Answers (2)

AlexK
AlexK

Reputation: 1281

You need something along the lines of vector <vector <int> > with inside vector representing a full row. Or a full column (just pick a row major or a column major and stick with it). Or, just use boost::multi_array (http://www.boost.org/doc/libs/1_53_0/libs/multi_array/doc/user.html)

Here is an example:

//#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;

int main(){

vector <vector <int> > my2d;

vector<int> row;

row.push_back(1); row.push_back(2); row.push_back(3);

my2d.push_back(row);

++row[1];

my2d.push_back(row);

--row[0];

my2d.push_back(row);

for(size_t r=0;r<my2d.size();r++)
{
    for(size_t c=0;c<my2d[0].size();c++)
    {
        printf("%d ",my2d[r][c]);
    }
    printf("\n");
}

getchar();

return 0;
}

Upvotes: 1

Boris
Boris

Reputation: 622

One more way to work with 2D-arrays is the using of one vector with 2D-addressing in your own class.

Here an example:

#include <iostream>
#include <vector>

class array_2d
{
    public:
        array_2d( 
            unsigned int x, 
            unsigned int y ) 
        : 
            m_size_x( x ), 
            m_size_y( y ),
            // resize vector to size x*y, all elements are 0.
            m_data( x*y, 0 )
        {}

        int
        get( unsigned int x, unsigned int y ) const
        {
            return m_data[ x + y * m_size_y ];
        }

        void
        set( unsigned int x, unsigned int y, int data )
        {
            m_data[ x + y * m_size_y ] = data;
        }

    private:
        unsigned int m_size_x;
        unsigned int m_size_y;

        std::vector <int> m_data;
};

int main()
{
    // 2D array 2x3.
    array_2d m( 2, 3 );

    // Set 2 cells into 1 and 3.
    m.set( 1, 1, 1 );
    m.set( 2, 0, 3 );

    for( unsigned int i = 0; i < 3; ++i )
    {
        for( unsigned int j = 0; j < 2; ++j )
            std::cout << m.get( i, j ) << " ";

        std::cout << std::endl;
    }
    return 0;
}

Upvotes: 3

Related Questions