0

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.

4

2 回答 2

3

使用 2D 数组的另一种方法是在您自己的类中使用一个具有 2D 寻址的向量。

这里有一个例子:

#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;
}
于 2013-06-06T23:15:27.177 回答
1

您需要类似于vector <vector <int> >表示整行的内部向量的东西。或一整列(只需选择行专业或列专业并坚持下去)。或者,只需使用 boost::multi_array ( http://www.boost.org/doc/libs/1_53_0/libs/multi_array/doc/user.html )

这是一个例子:

//#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;
}
于 2013-06-06T22:49:32.467 回答