Returning arrays and vectors

Why can I return vectors, and the method returns all elements, but return cannot do the same with array?

While std::vector<T> is a copyable type, an array is not copyable;
so we can't return an array by value from a function.

It is possible to wrap the array inside a user-defined class type which can then be copied.
This is essentially what std::array does.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <vector>
#include <array>
#include <iostream>

std::vector<int> foo() { return { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ; } // return vector by value

std::array<int,10> bar() { return { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } ; } // return std::array by value

int main()
{
    for( int v : foo() ) std::cout << v << ' ' ; // 0 1 2 3 4 5 6 7 8 9
    std::cout << '\n' ;

    for( int v : bar() ) std::cout << v << ' ' ; // 0 1 2 3 4 5 6 7 8 9
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/aae4fc0ada17ba0b
Topic archived. No new replies allowed.