Home > Software engineering >  How to return a vector of vectors from a function?
How to return a vector of vectors from a function?

Time:05-08

When I try to return a vector of vectors 'arr' from the add() like this

void add(int cols, int rows){
    std::vector<std::vector<int>> arr;
    //do something
    return arr;
}
int main(){
    std::vector<std::vector<int>> vec;
    vec=add(4,4);   
    return 0;
}

The compiler gives the following error message:

main.cpp:20:12: error: return-statement with a value, in function returning ‘void’ [-fpermissive]
   20 |     return arr;
      |            ^~~
main.cpp: In function ‘int main()’:
main.cpp:26:16: error: no match for ‘operator=’ (operand types are ‘std::vector >’ and ‘void’)
   26 |     vec=add(4,4);
      |                ^

CodePudding user response:

The problem is that the return type of your function(as specified while defining the function) is void but you're returning arr which is of type std::vector<std::vector<int>>.

To solve this just change the return type of the function to std::vector<std::vector<int>> as shown below:

//vvvvvvvvvvvvvvvvvvvvvvvvvvvvv------------------------>return type changed from void
  std::vector<std::vector<int>> add(int cols, int rows){
    std::vector<std::vector<int>> arr;
    //do something
    return arr;
}

CodePudding user response:

The return type for function add is void, thus you cannot return any value, in order to return a value you will have make the return type the type of the value, thus the return type will have to be std::vectorstd::vector<int> for you to be able to return the value.

  • Related