Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c++ - Two dimensional array using vector

I want to create 2D array using vector. But, when I do this, I get seg fault. Can anyone please explain what I am doing wrong, and possible solution for this problem.

I made everything public since I dont want to deal with getters and setters now. I want to get the concept of 2D array clear.

#include <iostream>
#include <vector>
using namespace std;

class point
{   
    public:
        point():x(0),y(0){}
        ~point(){}
        point(float xx,float yy):x(xx),y(yy){}
        float x,y;
};

int main()
{
    vector<vector<point> > a; // 2D array
    point p(2,3);
    a[0][0] = p; // error here
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your vector is empty. So you can't use [0][0].

Here is how you declare it:

a.push_back(vector<point>());
a[0].push_back(p);

If you know how many items you will have from the start, you can do :

vector<vector<point> > a(10, vector<point>(10));

It's a vector containing 10 vectors containing 10 point. Then you can use

a[4][4] = p;

However, I believe that using vector of vectors is confusing. If you want an array, consider using uBLAS http://www.boost.org/doc/libs/1_41_0/libs/numeric/ublas/doc/index.htm

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

int main () {
    using namespace boost::numeric::ublas;
    matrix<double> m (3, 3);
    for (unsigned i = 0; i < m.size1 (); ++ i)
        for (unsigned j = 0; j < m.size2 (); ++ j)
            m (i, j) = 3 * i + j;
    std::cout << m << std::endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...