一个向量的向量的初始化方法?

17

有没有一种类似于初始化矩阵的快速方法来初始化向量的向量?

typedef int type;

type matrix[2][2]=
{
{1,0},{0,1}
};

vector<vector<type> > vectorMatrix;  //???
4个回答

7
对于单个向量,您可以使用以下内容:
typedef int type;
type elements[] = {0,1,2,3,4,5,6,7,8,9};
vector<int> vec(elements, elements + sizeof(elements) / sizeof(type) );

基于此,您可以使用以下内容:

type matrix[2][2]=
{
   {1,0},{0,1}
};

vector<int> row_0_vec(matrix[0], matrix[0] + sizeof(matrix[0]) / sizeof(type) );

vector<int> row_1_vec(matrix[1], matrix[1] + sizeof(matrix[1]) / sizeof(type) );

vector<vector<type> > vectorMatrix;
vectorMatrix.push_back(row_0_vec);
vectorMatrix.push_back(row_1_vec);

c++0x 中,您可以像数组一样初始化标准容器。

4
std::vector<std::vector<int>> vector_of_vectors;

如果您想添加内容,可以使用以下步骤:

vector_of_vectors.resize(#rows); //just changed the number of rows in the vector
vector_of_vectors[row#].push_back(someInt); //this adds a column

或者你可以像这样做:

或者您可以这样做:

std::vector<int> myRow;
myRow.push_back(someInt);
vector_of_vectors.push_back(myRow);

因此,在您的情况下,您应该能够说:
vector_of_vectors.resize(2);
vector_of_vectors[0].resize(2);
vector_of_vectors[1].resize(2);
for(int i=0; i < 2; i++)
 for(int j=0; j < 2; j++)
   vector_of_vectors[i][j] = yourInt;

3

在C++0x中,我认为可以使用与您的matrix相同的语法。

在C++03中,您需要编写一些繁琐的代码来填充它。Boost.Assign可能能够简化它,使用以下未经测试的代码:

#include <boost/assign/std/vector.hpp>

vector<vector<type> > v;
v += list_of(1)(0), list_of(0)(1);

甚至更多
vector<vector<type> > v = list_of(list_of(1)(0))(list_of(0)(1));

我尝试过了,但似乎不起作用。我有一个 vector<vector<int>,我想将变量的第一个元素初始化为1,这样我就有了一个只有一个元素的向量,它被初始化为1。提前感谢您。 - saloua
在C++11中,可以这样写:vector<vector<int>> v {{1}};。在C++03中,使用Boost.Assign库,可以这样写:vector<vector<int> > v = list_of(list_of(1));。如果这些方法都不行,请提出一个新问题,展示你的尝试,并描述出现了什么问题。 - Mike Seymour
我尝试过 vector<vector<int> > v(10); v+= list_of(list_of(1));vector<vector<int> > v(10); v = list_of(list_of(1));,但是编译出错了。我认为使用 repeat 会更好,但我不知道怎么用。我将提一个新问题。谢谢。 - saloua

2
如果矩阵完全填满 -
vector< vector<int> > TwoDVec(ROWS, vector<int>(COLS));
//Returns a matrix of dimensions ROWS*COLS with all elements as 0
//Initialize as -
TwoDVec[0][0] = 0;
TwoDVec[0][1] = 1;
..
.

更新:我发现有一种更好的方法在这里

否则,如果每行中有可变数量的元素(不是矩阵)-

vector< vector<int> > TwoDVec(ROWS);
for(int i=0; i<ROWS; i++){
    while(there_are_elements_in_row[i]){           //pseudocode
        TwoDVec[i].push_back(element);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接