c++ - 如何: return multidimensional vector (Matrix) from function - using header

标签 c++ matrix return

我想使用一个函数从 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

我的错误是什么?

错误列表暗示存在重大错误。感谢您的帮助。请温柔点,这里的新手。

最佳答案

  1. 如果您没有 using namespace std;,则需要在 header 中为 vector 添加前缀 std::vector在 include 指令之前。无论如何,在 header 中包含 std:: 是一种很好的做法。

  2. 主要应该是

    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/

相关文章:

c++ - 从没有参数的函数返回整数数组

c++ - 如何在 'nmixures' 中设置 'bShadowDetection' 和 'BackgroundSubtractorMOG2' 值?

c++ - 类对象为 float 类型

r - 密度图矩阵,每个图覆盖两个分布

C++ 创建子矩阵

java - 原地旋转 NxN 矩阵 90 度时出现逻辑错误

c - 从 double 函数返回 void?

c++ - 运算符 << : std::cout << i << (i << 1);

c++ - (bool)(i & 1) 和 i % 2 == 1 相同吗?

jquery - 当点击 'enter/return' 时运行 jQuery AJAX