如何实现二维向量数组?

2021-12-21 00:00:00 vector c++

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

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?

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

vector< int* > my ints;
int add;

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

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

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

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

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)?

推荐答案

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

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:

// 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?

相关文章