从C++中的函数返回一个向量或数组
Return a vector or array from a function in C++
由于用户输入,我想创建一个创建N矩阵的程序,但我需要返回向量(或数组)值,然后将它们发送到函数,然后通过返回向量来获取。
例如:
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++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 如何按另一个向量的方向调整一个向量?
- 将字符向量复制到另一个向量
- 制作一对共享指针并推送一个向量
- 你能把一个向量<int64>投射到一个向量<uint8>吗
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- 如何将所有指针从一个向量移动到另一个向量?
- 将一个向量映射到不同的对,即使向量映射到每对时是不同的?
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 使用步骤c++构建一个向量
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 将一个向量对放在一个无序映射与一个映射中