2013-11-22 57 views
0

我正在写的程序的一部分要求我设置矢量矢量,以便成为维度为5的方形矩阵。尝试打印时似乎没有输出出矢量,我不知道为什么。有小费吗?使用矢量向量设置单位矩阵C++

#include<string> 
#include<cstdlib> 
#include<fstream> 
#include<vector> 
#include<iostream> 
using namespace std; 

int main(){ 
int rows=5; 
vector< vector<double> > identity; // declare another vector of vectors, which   initially will be 
// the identity matrix of the same dimensions as 'matrix'. 

    for (int j=0; j<rows; j++) {//set up the identity matrix using the Kronecker Delta  relation. If row == col, then =1. Else =0. 
     vector<double> temp2; // temporary vector to push onto identity 
     identity.push_back(temp2); 
     for (int k=0; k<rows; k++){ 
      if(j==k) { 
      temp2.push_back(1); 
      } 
      else { 
      temp2.push_back(0); 
      } 
     } 
     identity.push_back(temp2); 
    } 
    // print out identity 
    for (int j=0; j<identity.size(); j++) { 
     for (int k=0; k<identity[0].size(); k++) { 
      cout<<' '<<identity[j][k]; 
     } 
     cout<<endl; 
    } 
} 
+0

你为什么将'temp2'推到'identity'上两次? –

+0

哎呀,我现在检查一下。编辑:这工作,我知道我一定是一直在某个地方愚蠢。干杯:) – user3000403

+0

这是你的错误。 '身份[0] .size()'为0. –

回答

1
vector<double> temp2; // temporary vector to push onto identity 
    identity.push_back(temp2); 
    for (int k=0; k<rows; k++){ 
     if(j==k) { 
     temp2.push_back(1); 

当你推到TEMP2顶层载体,它是复制。 之后更改temp2对该身份向量拥有的副本没有影响。现在

,你填充它后做推TEMP2 再次,但身份的第一个项目将是大小为零的默认初始化向量。结构你实际上填充这个样子的:

{{}, 
    {1, 0, 0, 0, 0}, 
    {}, 
    {0, 1, 0, 0, 0}, 
    {}, 
    {0, 0, 1, 0, 0}, 
    {}, 
    {0, 0, 0, 1, 0}, 
    {}, 
    {0, 0, 0, 0, 1}} 

所以,你的循环

for (int j=0; j<identity.size(); j++) { 
    for (int k=0; k<identity[0].size(); k++) { 

绝不会做任何事情,因为identity[0].size()始终为零。


TL; DR: 只是移除第一identity.push_back(temp2)线。

+0

感谢您的回复,我明白为什么它现在不起作用。 – user3000403