C++ 使用向量的二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1833127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:19:34  来源:igfitidea点击:

Two dimensional array using vector

c++stl

提问by Curious

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.

我公开了所有内容,因为我现在不想处理 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;
}

回答by Tristram Gr?bener

Your vector is empty. So you can't use [0][0].

你的向量是空的。所以你不能使用[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

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

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

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

回答by wheaties

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

这是另一个建议。您要完成的工作以前已经完成,可以在Boost Multi-Array 中找到

回答by jlarcombe

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.

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

回答by Jerry Coffin

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 usethe 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.

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

回答by Sai Charan

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

最简单的方法是使用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]<<" ";

回答by Sunil Seetharam

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

设法让它工作。从其他地方获得了“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;
}

回答by wcochran

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

你可以使用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                                                    

回答by Behnam Dezfouli

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

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

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

回答by himanshu chauhan

The simplest way to use vector as C-style array

将向量用作 C 样式数组的最简单方法

int z =0;
vector<vector<int>> vec(5,5);
for(int i =0; i < 5; i++)
{       
    for(int j=0; j<5; j++)
    {
        vec[i][j] = ++z;
    }
}


for(int i =0; i < x; i++)
{

    for(int j=0; j<x; j++)
    {
        cout<<vec[i][j]<<" ";
    }

}