user3000403
user3000403

Reputation: 7

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

Part of a program I am writing requires me to set up a vector of vectors, to be a square matrix of dimensions 5. There seems to be no output when trying to print out the vector and I don't know why. Any tips?

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

Upvotes: 0

Views: 2161

Answers (1)

Useless
Useless

Reputation: 67743

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

When you push temp2 into your top-level vector, it is copied. Changing temp2 afterwards has no effect on that copy, which is owned by the identity vector.

Now, you do push temp2 again after populating it, but the first item in identity will be a default-initialized vector with zero size. The structure you're actually populating looks like this:

 {{},
  {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}}

So, your loop

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

will never do anything, because identity[0].size() is always zero.


tl;dr: just remove the first identity.push_back(temp2) line.

Upvotes: 1

Related Questions