首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从C++中的函数返回向量或数组

从C++中的函数返回向量或数组
EN

Stack Overflow用户
提问于 2016-05-06 13:10:14
回答 1查看 1.2K关注 0票数 2

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

代码语言:javascript
复制
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;
}

这是一种更好的方法吗?在进阶时谢谢。

EN

回答 1

Stack Overflow用户

发布于 2016-05-06 13:26:06

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

代码语言:javascript
复制
#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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37064662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档