Two dimensional array using vector

Question

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;
}
``````
1
22
12/7/2017 10:13:27 AM

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;
}
``````
48
7/3/2015 10:59:25 AM