2010-06-17 113 views
16

有没有办法以初始化矩阵的方式初始化矢量矢量?矢量矢量的初始化?

typedef int type; 

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

vector<vector<type> > vectorMatrix; //??? 

回答

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,你可以初始化一个标准集装箱与数组相同的方式。

+0

该解决方案与我的想法非常相似。 – Eric 2010-06-17 12:15:34

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)); 
+0

我试过了,但它似乎没有工作。我有一个'vector ',我想将变量的第一个元素初始化为一个,这样我就可以将一个元素向量初始化为一个向量。 在此先感谢。 – saloua 2012-10-29 11:33:22

+0

@tuxworker:在C++ 11中,这是'vector > v {{1}};'。使用C++ 03中的Boost.Assign,类似于'vector > v = list_of(list_of(1));'。如果这不起作用,请提出一个新问题,显示您正在尝试的内容并描述出了什么问题。 – 2012-10-29 11:36:29

+0

确实我试过'vector > v(10); v + = list_of(list_of(1));'和'vector > v(10); v = list_of(list_of(1));'并且我有一个编译错误。我认为除了重复使用它会更好,但我不知道如何。我会问一个新问题。谢谢 – saloua 2012-10-29 11:53:24

3
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; 
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; 
.. 
. 

更新:我发现有一个更好的办法here

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

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