Search code examples
c++recursionvector2dpush-back

Why cant you push_back in 2D vector? c++


I am learning recursion in c++ and was stuck on why you cant simply use the .push_back() instead of creating a function to copy the specific_previous_result elements, then .push_back().

vector<vector<int>> get_every_n_elements(vector<int> arr, int n) {
if (n == 0) {
    vector<vector<int>> result;

    vector<int> empty_list;
    result.push_back(empty_list);

    return result;
}

vector<vector<int>> previous_result = get_every_n_elements(arr, n - 1);

vector<vector<int>> current_result; //empty

for (auto specific_previous_result : previous_result) { // [[]] -> []

    for (auto elem : arr) { // [1,2,3,4] -> 1
      //current_result.push_back(specific_previous_result.push_back(elem));
      //This does not work^^

      current_result.push_back(group(specific_previous_result, elem));
      //The group function copies all elements to newVec and push_back(elem) after
      //Then returns newVec with elem at the end
    }

}

return current_result;
}

The error that I get when I run the push_back line is error: invalid use of void expression current_result.push_back(specific_previous_result.push_back(elem));. Thank you for your help.


Solution

  • There doesn't seem to be a valid reason to return the vector itself after a push_back. Sometimes it's useful, but most of the time, it is not. I would recommend writing it in two lines, which is also more clearer IMO than a separate (and inefficient!) function:

    current_result.push_back(specific_previous_result);
    current_result.back().push_back(elem);