Can we create temporary pass-in `std::vector<int>` parameter?

In C++11 you can just do:

void PrintNow(const std::vector<int> &v)
{
    std::cout << v[0] << std::endl;
}

PrintNow({20});

VS2010 doesn't yet support this part of C++11 though. (gcc 4.4 and clang 3.1 do)

If you only need a single element then in C++03 you can do:

PrintNow(std::vector<int>(1,20));

If you need more than one element then I don't think there's any one line solution. You could do this:

{ // introduce scope to limit array lifetime
    int arr[] = {20,1,2,3};
    PrintNow(std::vector<int>(arr,arr+sizeof(arr)/sizeof(*arr));
}

Or you could write a varargs function that takes a list of ints and returns a vector. Unless you use this a lot though I don't know that it's worth it.


The problem is that std::vector::push_back() returns void, not that you can't pass a temporary to the function.


The error is generated because the return type of std::vector::push_back function is void:

void push_back ( const T& x );

Try the following:

PrintNow(std::vector<int>(1, 20));

The code above uses one of the available constructors of std::vector class:

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );

Tags:

C++