如何:从函数返回多维向量(矩阵) - 使用标题

时间:2016-11-08 14:03:21

标签: 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

我的错误是什么?

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

2 个答案:

答案 0 :(得分:1)

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

  2. 主要应该是

    int main(){
    
        vector<vector<double>> matrix = matrix_read();
    
        Sleep(60000);
        return 0;
    }
    
  3. 即。将对象matrix设置为函数的返回值。否则,您将在main函数中为matrix_read定义另一个原型。

答案 1 :(得分: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;
    }