使用向量C++中的一个向量建立一个单位矩阵

Set up an identity matrix using a vector of vectors C++

本文关键字:一个 向量 单位 建立 C++      更新时间:2023-10-16

我正在编写的程序的一部分要求我设置一个向量的向量,为5维的方阵。当试图打印出矢量时,似乎没有输出,我不知道为什么。有什么建议吗?

#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;
    }
}
    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;博士:仅移除第一条CCD_ 2线。