gpt4 book ai didi

c++ - 使用 vector C++ 的 vector 设置单位矩阵

转载 作者:行者123 更新时间:2023-11-28 07:16:32 24 4
gpt4 key购买 nike

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

#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 压入您的顶级 vector 时,它被复制。之后更改 temp2 对该拷贝没有影响,该拷贝由身份 vector 拥有。

现在,您确实在填充后 再次 推送 temp2,但身份中的第一项将是一个默认初始化的 vector ,大小为零。您实际填充的结构如下所示:

 {{},
{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() 总是零。


长话短说:只需删除第一个 identity.push_back(temp2) 行。

关于c++ - 使用 vector C++ 的 vector 设置单位矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20151749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com