使用向量C++中的一个向量建立一个单位矩阵
Set up an identity matrix using a vector of vectors C++
我正在编写的程序的一部分要求我设置一个向量的向量,为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线。
相关文章:
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为什么一个向量上的多线程操作很慢
- 将一个向量插入另一个向量的某个位置
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 如何按另一个向量的方向调整一个向量?
- 将字符向量复制到另一个向量
- 制作一对共享指针并推送一个向量
- 你能把一个向量<int64>投射到一个向量<uint8>吗
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- 如何将所有指针从一个向量移动到另一个向量?
- 将一个向量映射到不同的对,即使向量映射到每对时是不同的?
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 使用步骤c++构建一个向量
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 将一个向量对放在一个无序映射与一个映射中