C++ 如何实现二维向量数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9694838/
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 13:10:26  来源:igfitidea点击:

How to implement 2D vector array?

c++vector

提问by John Smith

I'm using the vector class in the STL library for the first time. How should I add to a specific row of the vector array?

我是第一次使用 STL 库中的向量类。我应该如何添加到向量数组的特定行?

struct x{
     vector <vector <int> > v;
     int row;
 };

vector< int* > my ints;
int add;

if i wanted to add to first row of v with the first pointer of integers, could I do

如果我想用第一个整数指针添加到 v 的第一行,我可以做

myints[0]->v[myints[0]->row].push_back(add);

Is this method fine to create a 2 D vector of vector ints where each row could potentially be of different length (i.e. have a different number of columns)?

这种方法是否适合创建向量ints 的二维向量,其中每行可能具有不同的长度(即具有不同的列数)?

回答by Moritz

I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:

我不确定问题是什么,因为您的示例代码有几个错误,并没有真正说明您要做什么。但这是添加到 2D 矢量的特定行的方法:

// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);

Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?

这回答了你的问题了吗?如果没有,您能否尝试更具体地说明您遇到的问题?

回答by Roi Danton

If you know the (maximum) number of rows and columns beforehand, you can use resize()to initialize a vector of vectors and then modify (and access) elements with operator[]. Example:

如果您事先知道(最大)行数和列数,则可以使用resize()来初始化向量向量,然后使用operator[]. 例子:

int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;

std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));

// Read from matrix.
int value = matrix[1][2];

// Save to matrix.
matrix[3][1] = 5;

Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column].

另一种可能性是仅使用一个向量并将 id 拆分为多个变量,访问如vector[(row * columns) + column].

回答by Aditya Goel

Just use the following methods to create a 2-D vector.

只需使用以下方法来创建二维向量。

int rows, columns;        

// . . .

vector < vector < int > > Matrix(rows, vector< int >(columns,0));

OR

或者

vector < vector < int > > Matrix;

Matrix.assign(rows, vector < int >(columns, 0));

//Do your stuff here...

This will create a Matrix of size rows * columnsand initializes it with zerosbecause we are passing a zero(0) as a second argument in the constructor i.e vector < int > (columns, 0).

这将创建一个大小为rows * columns的矩阵并用初始化它,因为我们在构造函数中传递了一个 zero(0) 作为第二个参数,即vector < int > (columns, 0)

回答by Madhurya Gandi

//initialize the 2D vector first

//首先初始化二维向量

vector<vector<int>> matrix;

vector<vector<int>> matrix;

//initialize the 1D vector you would like to insert into matrix

//初始化要插入矩阵的一维向量

vector<int> row;

vector<int> row;

//initializing row with values

//用值初始化行

row.push_back(val1);

row.push_back(val1);

row.push_back(val2);

row.push_back(val2);

//now inserting values into matrix

//现在将值插入矩阵

matrix.push_back(row);

matrix.push_back(row);

//output- [[val1,val2]]

//输出- [[val1,val2]]

回答by rashedcs

We can easily use vector as 2d array. We use resize() method for this purpose. The code below can be helpful to understand this issue.

我们可以轻松地将向量用作二维数组。为此,我们使用 resize() 方法。下面的代码有助于理解这个问题。

Code Snippet :

代码片段:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    int row, col;
    cin>>row>>col;

    vector <vector<int>> v;
    v.resize(col,vector<int>(row));

    //v = {{1,2,3}, {4,5,6}, {7,8,9}}; 

    /** input from use **/
    for(int i=0; i<row; i++)
    {
       for(int j=0; j<col; j++)
       {
          cin>>v[i][j];
       }
    }

    for(int i=0;i<row; i++)
    {
       for(int j=0;j<col;j++)
       {
          cout<<v[i][j]<<" ";
       }
    }
    return 0;
}

回答by Varun Garg

Another way to define a 2-d vector is to declare a vector of pair's.

另一种定义二维向量的方法是声明一个成对向量。

 vector < pair<int,int> > v;

**To insert values**
 cin >> x >>y;
 v.push_back(make_pair(x,y));

**Retrieve Values**
 i=0 to size(v)
 x=v[i].first;
 y=v[i].second;

For 3-d vectors take a look at tuple and make_tuple.

对于 3-d 向量,请查看 tuple 和 make_tuple。

回答by Ridowan Ahmed

I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .

我使用这段代码。对我来说很好用。复制它并在您的计算机上运行。你自己就明白了。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector <vector <int> > matrix;
    size_t row=3 , col=3 ;
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            vector <int> colVector ;
            matrix.push_back(colVector) ;
            matrix.at(i).push_back(cnt++) ;
        }
    }
    matrix.at(1).at(1) = 0;     //matrix.at(columns).at(rows) = intValue 
    //printing all elements
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            cout<<matrix[i][j] <<" " ;
        }
        cout<<endl ;
    }
}