How to Return a Vector From a Function in C++

  1. Use the vector<T> func() Notation to Return Vector From a Function
  2. Use the vector<T> &func() Notation to Return Vector From a Function

This article will introduce how to return a vector from a function efficiently in C++.

Use the vector<T> func() Notation to Return Vector From a Function

The return by value is the preferred method if we return a vector variable declared in the function. The efficiency of this method comes from its move-semantics. It means that returning a vector does not copy the object, thus avoiding wasting extra speed/space. Under the hood, it points the pointer to the returned vector object, thus providing faster program execution time than copying the whole structure or class would have taken.

#include <iostream>
#include <vector>
#include <iterator>

using std::cout; using std::endl;
using std::vector;

vector<int> multiplyByFour(vector<int> &arr)
{
    vector<int> mult;
    mult.reserve(arr.size());

    for (const auto &i : arr) {
        mult.push_back(i * 4);
    }
    return mult;
}

int main() {
    vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
    vector<int> arrby4;

    arrby4 = multiplyByFour(arr);

    cout << "arr    - | ";
    copy(arr.begin(), arr.end(),
         std::ostream_iterator<int>(cout," | "));
    cout << endl;
    cout << "arrby4 - | ";
    copy(arrby4.begin(), arrby4.end(),
         std::ostream_iterator<int>(cout," | "));
    cout << endl;


    return EXIT_SUCCESS;
}

Output:

arr    - | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
arrby4 - | 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 |

Use the vector<T> &func() Notation to Return Vector From a Function

This method uses the return by reference notation, which is best suited for returning large structs and classes. Note that do not return the reference of the local variable declared in the function itself because it leads to a dangling reference. In the following example, we pass the arr vector by reference and return it also as a reference.

#include <iostream>
#include <vector>
#include <iterator>

using std::cout; using std::endl;
using std::vector;

vector<int> &multiplyByFive(vector<int> &arr)
{
    for (auto &i : arr) {
        i *= 5;
    }
    return arr;
}

int main() {
    vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
    vector<int> arrby5;

    cout << "arr    - | ";
    copy(arr.begin(), arr.end(),
         std::ostream_iterator<int>(cout," | "));
    cout << endl;

    arrby5 = multiplyByFive(arr);

    cout << "arrby5 - | ";
    copy(arrby5.begin(), arrby5.end(),
         std::ostream_iterator<int>(cout," | "));
    cout << endl;

    return EXIT_SUCCESS;
}

Output:

arr    - | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
arrby5 - | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 |

Related Article - C++ Vector

  • How to Initialize a Vector in C++