tags:

views:

687

answers:

4

Hi, 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.

Thanks.

#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;
}
+10  A: 

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 begining, you can do :

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

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

a[4][4] = p;

However, I belive that using vector of vectors is confusing. If you want an array, consider using ublas http://www.boost.org/doc/libs/1%5F41%5F0/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;
}
Tristram Gräbener
thanks, and for additional info, it was helpful :)
Curious
If you have your answer, mark it as such. Otherwise state what extra informatino you need ;)
Tristram Gräbener
+1  A: 

You're creating your 2D array just fine. The problem is that when you create it, it's an empty array -- it doesn't hold any points at all yet. You try to use the point at [0][0] before you've actually created a point there. Normally, to put a new element into a vector, you use resize() to set the size of the vector, or push_back() to add items one at a time. In this case, the latter will probably be a bit clumsy -- since you have a vector of vectors of point, you need to create a vector of point, push a point onto that vector, then push that vector onto your array.

Jerry Coffin
+2  A: 

You have constructed a vector of vectors that is empty, and have tried to dereference the first element without adding any elements to it.

Vectors don't work like (some) associative arrays, where attempting to access a value that's missing will add it to the collection. You need to ensure the vectors have an appropriate number of entries before you try to access them by using the appropriate form of the vector constructor or by using push_back.

jlarcombe
+6  A: 

Here's another suggestion. What you're trying to accomplish has been done before and can be found within the Boost Multi-Array.

wheaties