gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:26:14 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com