2016-11-08 90 views
0

我想从cin中读取矩阵,使用函数,然后将矩阵返回到main。如何从函数返回多维向量(矩阵) - 使用头文件

这里是我的代码:

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

供参考: Return multidimensional vector from function for use in main, how to use correctly?

Error list

什么是我的错误?

错误列表意味着存在一个重大错误。感谢您的帮助。请在这里温柔,新手。

+0

''>>是在C++中的运算符,放一个你的变量和函数定义中的空间。 –

+1

在'mymath.h'头文件中,什么是'vector'?想一会儿吧。 –

回答

0
  1. 您需要在头与std::vector前缀vector,如果你没有using namespace std;之前include指令。无论如何,最好在头文件中有std::

  2. 在主,应该是

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

即你的对象matrix设置为函数的返回值。否则,您将在主函数中为matrix_read定义另一个原型。

+0

感谢您的回答。这工作得很好。我将发布现在工作的代码作为答案。 –

0

MaximilianMatthé是对的。这里的工作代码:

mymath.h

#pragma once 
#include <vector> 
#include <iostream> 

std::vector<std::vector<double>> matrix_read(); 

mymath.cpp

#include "mymath.h" 


std::vector<std::vector<double>> matrix_read() { 

std::cout << "How big is the quadratic matrix A?\n"; 
int n; 
//row&column size A 
std::cin >> n; 
    std::vector<std::vector<double>> A(n, std::vector<double>(n)); 

     //fill matrix A 
     int j = 0; 
     for (int i = 0; i < n; i++) { 

      for (int j = 0; j < n; j++) { 
       std::cout << "Please enter the value for A" << "[" << i + 1 << "]" << "[" << j + 1 << "]\n"; 
       std::cin >> A[i][j]; 
      } 
     } 
     //control matrix A: 
     std::cout << "Please be sure this is the correct Matrix A: \n\n"; 
     for (int i = 0; i < n; i++) { 
     for (int j = 0; j < n; j++) { 
      std::cout << A[i][j] << " "; 
      } 
     std::cout << std::endl; 
     } 
return A; 
} 

的main.cpp

#include <windows.h> 

    #include "mymath.h" 

    int main() { 

     std::vector<std::vector<double>> A = matrix_read(); 

    Sleep(60000); 
    return 0; 
    }