使用向量的二维数组 [英] Two dimensional array using vector
问题描述
我想使用矢量创建2D数组。但是,当我这样做时,我会遇到段错误。
谁能解释我做错了什么,以及对此问题的可能解决方案。
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.
我公开了所有内容,因为我不想与getter和setter方法打交道。现在。
我想弄清楚2D阵列的概念。
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]
。
Your vector is empty. So you can't use [0][0]
.
这是您的声明方式:
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;
但是,我相信使用向量vector会造成混淆。如果需要数组,请考虑使用uBLAS http: //www.boost.org/doc/libs/1_41_0/libs/numeric/ublas/doc/index.htm
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;
}
这篇关于使用向量的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!