Search code examples
c++matrixreturn

How to: return multidimensional vector (Matrix) from function - using header


I'd like to read a matrix from cin, using a function, then return matrix back to main.

Here's my code:

main.cpp

#include <iostream>
#include <windows.h>
#include <vector>
#include "mymath.h"
using namespace std;

int main(){

vector<vector<double>> matrix_read();

Sleep(60000);
return 0;
}

mymath.h

#pragma once
#ifndef MYMATH_H
#define MYMATH_H
vector<vector<double>> matrix_read();
#endif

mymath.cpp

#include "mymath.h"
#include <vector>
#include <iostream>
using namespace std;


vector<vector<double>> matrix_read() {

        cout << "How big is the quadratic matrix A?\n";
        int n;
        //row&column size A
        cin >> n;
        vector<vector<double>> A(n, vector<double>(n));
        //fill matrix A
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cin >> A[i][j];
            }
        }
        //control matrix A:
        cout << "Please be sure this is the correct Matrix A: \n";
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cout << A[i][j] << " ";
            }
        cout << endl;
        }
return A;
}

for reference: Return multidimensional vector from function for use in main, how to use correctly?

Error list

What is my error?

The error list implies there's a major mistake. Thank you for your help. Please be gentle, newbie here.


Solution

    1. You need to prefix vector with std::vector in the header, if you did not have using namespace std; before the include directive. Anyway, it's good practice to have std:: in the header.

    2. In main, it should be

      int main(){
      
          vector<vector<double>> matrix = matrix_read();
      
          Sleep(60000);
          return 0;
      }
      

    i.e. you set the object matrix to the return value of the function. Otherwise, you would define another prototype for matrix_read in the main function.