使用向量的二维数组

发布于 2024-08-13 08:37:02 字数 500 浏览 5 评论 0原文

我想使用向量创建二维数组。但是,当我这样做时,我遇到了段错误。 谁能解释一下我做错了什么,以及这个问题的可能解决方案。

我将所有内容公开,因为我现在不想处理 getter 和 setter。 我想弄清楚二维数组的概念。

#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;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

蓝色星空 2024-08-20 08:37:03

你的向量是空的。所以你不能使用[0][0]

声明方式如下:

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

如果您知道从一开始就有多少个项目,您可以这样做:

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

它是一个包含 10 个向量的向量,其中包含 10 个点。然后你可以使用

a[4][4] = p;

但是,我相信使用向量的向量是令人困惑的。如果您想要一个数组,请考虑使用 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;
}

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;
}
北方的韩爷 2024-08-20 08:37:03

这是另一个建议。您想要完成的任务之前已经完成,可以在 Boost 多阵列

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

巨坚强 2024-08-20 08:37:03

您构造了一个空的向量向量,并尝试取消引用第一个元素而不向其中添加任何元素。

向量不像(某些)关联数组那样工作,在关联数组中尝试访问缺少的值会将其添加到集合中。在尝试使用适当形式的向量构造函数或使用push_back 来访问向量之前,您需要确保向量具有适当数量的条目。

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.

债姬 2024-08-20 08:37:03

您正在创建二维数组,效果很好。问题是,当你创建它时,它是一个空数组——它根本不保存任何点。在实际创建点之前,您尝试使用 [0][0] 处的点。通常,要将新元素放入向量中,可以使用 resize() 设置向量的大小,或使用 push_back() 一次添加一项。在这种情况下,后者可能会有点笨拙 - 因为你有一个点向量的向量,你需要创建一个点向量,将一个点推到该向量上,然后将该向量推到你的数组上。

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.

流殇 2024-08-20 08:37:03

最简单的方法是使用 resize() 方法,如下所示:

vector <vector<int>> v;
cin>>n>>m; //n is rows and m is columns
v.resize(n,vector<int>(m));
for(i=0;i<n;i++)      // inserts elements into the vector v
 for(j=0;j<m;j++)
  cin>>v[i][j]; 

for(i=0;i<n;i++)      //accesses elements of vector v
 for(j=0;j<m;j++)
   cout<<v[i][j]<<" ";

The simplest way would be to use resize() method as follow:

vector <vector<int>> v;
cin>>n>>m; //n is rows and m is columns
v.resize(n,vector<int>(m));
for(i=0;i<n;i++)      // inserts elements into the vector v
 for(j=0;j<m;j++)
  cin>>v[i][j]; 

for(i=0;i<n;i++)      //accesses elements of vector v
 for(j=0;j<m;j++)
   cout<<v[i][j]<<" ";
挽清梦 2024-08-20 08:37:03

设法让它工作。从其他地方学到了“typedef”的想法。尝试下面的代码,它有效:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>


using namespace std;

int main()
{
    int i = 0;
    int j = 0;

///////////////////////////////////////////////////////////

    typedef vector<string> vecRow;
    typedef vector<vecRow> vecCol;

    vecRow vr;
    vecCol vc;
///////////////////////////////////////////////////////////
// Assigning string elements to the 2d array

    for(i=0;i<10;i++)
    {
            for(j=0;j<5;j++)
            {
                vr.push_back("string ["+to_string(i)+"]["+to_string(j)+"]");
            }
            vecRow vr_temp = vecRow(vr);
            vc.push_back(vr_temp);
            vr.clear();
    }

///////////////////////////////////////////////////////////
// Printing back the elements from the 2D array

    for(auto element : vc)
    {
            for(unsigned int ictr = 0;ictr < element.size() ; ictr++)
            {
                cout<<element[ictr]<<"\t";
            }
            cout<<endl;
    }

    getchar();
    return 0;
}

Managed to get it working. Picked up the idea for the 'typedef' from somewhere else. Try the below code, it works:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>


using namespace std;

int main()
{
    int i = 0;
    int j = 0;

///////////////////////////////////////////////////////////

    typedef vector<string> vecRow;
    typedef vector<vecRow> vecCol;

    vecRow vr;
    vecCol vc;
///////////////////////////////////////////////////////////
// Assigning string elements to the 2d array

    for(i=0;i<10;i++)
    {
            for(j=0;j<5;j++)
            {
                vr.push_back("string ["+to_string(i)+"]["+to_string(j)+"]");
            }
            vecRow vr_temp = vecRow(vr);
            vc.push_back(vr_temp);
            vr.clear();
    }

///////////////////////////////////////////////////////////
// Printing back the elements from the 2D array

    for(auto element : vc)
    {
            for(unsigned int ictr = 0;ictr < element.size() ; ictr++)
            {
                cout<<element[ictr]<<"\t";
            }
            cout<<endl;
    }

    getchar();
    return 0;
}
耳根太软 2024-08-20 08:37:03

您可以定义 vectorMatrix[][],它是向量矩阵,如下所示。

类:

class vectorMatrix
{
  std::vector<object> **cell;

  int columns;
  int rows;

  public:
  vectorMatrix(int columns, int rows);
  virtual ~vectorMatrix();

  void addCellAt(int row, int column, const object& entry);

  virtual std::vector<object>* getCell(int row, int column);

  void clearMatrix();
};

定义构造函数:

vectorMatrix::vectorMatrix(int columns, int rows)
{
   this->columns = columns;
   this->rows = rows;

   cell = new std::vector<object>* [columns];

   for (int i = 0; i < columns; i++)
   {
       cell[i] = new std::vector<object>[rows];
   }
}

添加条目的方法:

void vectorMatrix::addCellAt(int row, int column, const object& entry)
{
       cell[channel][timeSlot].push_back(entry);
}

获取指向给定行和列中向量的指针:

std::vector<object>* vectorMatrix::getCell(int row, int column)
{
    return &cell[row][column];
}

清除所有矩阵:

void vectorMatrix::clearMatrix()
{
    for (int tmpRow = 0; tmpRow < columns; tmpRow ++)
    {
        for(int tmpColumn = 0; tmpColumn < rows; tmpColumn ++)
        {
            cell[tmpRow][tmpColumn].clear();
        }
    }
}

You can define vectorMatrix[][], which is a matrix of vectors as follows.

Class:

class vectorMatrix
{
  std::vector<object> **cell;

  int columns;
  int rows;

  public:
  vectorMatrix(int columns, int rows);
  virtual ~vectorMatrix();

  void addCellAt(int row, int column, const object& entry);

  virtual std::vector<object>* getCell(int row, int column);

  void clearMatrix();
};

Define constructor:

vectorMatrix::vectorMatrix(int columns, int rows)
{
   this->columns = columns;
   this->rows = rows;

   cell = new std::vector<object>* [columns];

   for (int i = 0; i < columns; i++)
   {
       cell[i] = new std::vector<object>[rows];
   }
}

A method for adding an entry:

void vectorMatrix::addCellAt(int row, int column, const object& entry)
{
       cell[channel][timeSlot].push_back(entry);
}

Getting a pointer to the vector in a given row and column:

std::vector<object>* vectorMatrix::getCell(int row, int column)
{
    return &cell[row][column];
}

Clearing all the matrix:

void vectorMatrix::clearMatrix()
{
    for (int tmpRow = 0; tmpRow < columns; tmpRow ++)
    {
        for(int tmpColumn = 0; tmpColumn < rows; tmpColumn ++)
        {
            cell[tmpRow][tmpColumn].clear();
        }
    }
}
誰ツ都不明白 2024-08-20 08:37:03

您可以使用resize();例如,这里我将 a 的大小调整为 100 x 200 数组:

  vector<vector<point> > a; // 2D array                                         
  a.resize(100);
  for_each(a.begin(),a.end(),[](vector<point>& v){v.resize(200);});
  point p(2,3);
  a[0][0] = p; // ok now                                                    

You can use resize(); e.g., here I resize a to a 100 x 200 array:

  vector<vector<point> > a; // 2D array                                         
  a.resize(100);
  for_each(a.begin(),a.end(),[](vector<point>& v){v.resize(200);});
  point p(2,3);
  a[0][0] = p; // ok now                                                    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文