问题描述
我想使用向量创建二维数组。但是,当我这样做,我得到seg故障。
任何人都可以解释我做错了,可能解决这个问题。
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.
我把一切都公开,因为我不想处理getters和setter现在。
我想得到二维数组的概念清楚。
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;
}
推荐答案
所以你不能使用 [0] [0]
。
这是你如何声明它: p>
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));
这是一个包含10个矢量的矢量,包含10点。那么你可以使用
It's a vector containing 10 vectors containing 10 point. Then you can use
a[4][4] = p;
但是,我相信使用向量的向量是混乱的。如果您需要阵列,请考虑使用uBLAS
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;
}
这篇关于使用cpp中的向量的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!