我想使用一个函数从 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?
我的错误是什么?
错误列表暗示存在重大错误。感谢您的帮助。请温柔点,这里的新手。
最佳答案
如果您没有
using namespace std;
,则需要在 header 中为vector
添加前缀std::vector
在 include 指令之前。无论如何,在 header 中包含std::
是一种很好的做法。主要应该是
int main(){ vector<vector<double>> matrix = matrix_read(); Sleep(60000); return 0; }
即您将对象 matrix
设置为函数的返回值。否则,您将在 main 函数中为 matrix_read
定义另一个原型(prototype)。
关于c++ - 如何: return multidimensional vector (Matrix) from function - using header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488913/