2016-05-06 2 views
2

Я хочу создать программу, которая создает N-матрицу из-за ввода пользователем, но мне нужно вернуть значения вектора (или массива), а затем отправить их функции, и снова , получить по возвращении вектор. например:Возвращает вектор или массив из функции в C++

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; 
} 

Что это лучший способ сделать это? Заранее спасибо.

ответ

3

Если вы ищете способ построения 2-мерную структуру с использованием 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; 
} 
+0

@juanchopanza, да, 'reserve' не изменяет размером вектора, так что мне нужно 'resize'. Исправлен ответ –

+0

ОК, сейчас я удалю комментарии. КСТАТИ. вы можете пропустить цикл изменения размера, инициализируя вектор следующим образом: 'matrix_t Matrix (rows, vector (cols));'. См. Мой ответ на [этот старый вопрос] (http://stackoverflow.com/questions/12375591/vector-of-vectors-to-create-matrix). – juanchopanza

+0

@juanchopanza, ах, действительно, мы можем передать вектор как начальное значение элемента. –

Смежные вопросы