c++ - 从 C++ 函数返回 vector 或数组

标签 c++ arrays function matrix vector

我想创建一个程序,根据用户输入创建 N 矩阵,但我需要返回 vector (或数组)值,然后将它们发送到函数,然后再次通过返回 vector 来获取。

例如:

vector<int> createMatrix(rows, cols){
    for(int x = 0; x < rows; x++){
        for(int y = 0; y < cols; y++){
            cout << "Please, input the values for the row " << x << " and col " << y << endl;
            vector<int> Matrix(...)values;
            cin >> (...);
        }
    }
return Matrix; //here is the point
}

vector<int> mathOperations(operation, matrixA, matrixB){
    (...)
    return vector<int> resultMatrix;
}

int main(int argc, char *argv[]){
    int nMatrix, nRows, nCols;
    cout << "Please, answer how many matrix would you like do be created?" << endl;
    cin >> nMatrix;
    cout << "Thank you, and how many rows your matrix will have?" << endl;
    cin >> nRows;
    cout << "Thank you again, and how many cols?" << endl;
    cin >> nCols;
    cout << "Okey, creating " << nMatrix << " nMatrix for you!" << endl;

    for(int n = 0; n < nMatrix; n++){
        cout << "Please, insert the values for the matrix no" << n+1 << endl;
        vector<int> myMatrix[n] = createMatrix(nRows, nCols);
    }

    /* the rest of my code with functions to print values, create a new vectors by math operations between given arguments
    */

return 0;
}

最好的方法是什么?

最佳答案

如果您正在寻找一种使用 vector 构建二维结构的方法,请使用如下内容:

#include <vector>
#include <iostream>

using std::vector;
using std::cout;
using std::cin;

typedef vector<vector<int> > matrix_t;

matrix_t createMatrix(int rows, int cols){
  matrix_t Matrix(rows, vector<int>(cols));

  for(int x = 0; x < rows; x++){
    for(int y = 0; y < cols; y++){
      cout << "Please, input the values for the row "
        << x << " and col " << y << std::endl;
      cin >> Matrix[x][y];
    }
  }
  return Matrix;
}

int main(int argc, char const* argv[])
{
  matrix_t M(createMatrix(2, 2));

  for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++) {
      cout << M[i][j] << std::endl;
    }

  }

  return 0;
}

关于c++ - 从 C++ 函数返回 vector 或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064662/

相关文章:

c++ - 在 Qt 中创建/写入新文件

arrays - JSON 数组列转换为 JSON 对象

c - 参数名省略错误?

r - 如何创建可重用的plot_ly函数?

c++ - 使用 ifsream 和 stringstream 复制二进制文件时出错

c++ - 饱和减法/加法无符号字节

javascript - 循环遍历多级数组

javascript - JSON 到 XML 使用 Javascript

python - 通过字符串名称获取装饰函数对象

c++ - 不可复制类型的整数可索引 RAII 容器