Archie Gertsman
Archie Gertsman

Reputation: 1661

How to pass an r-value std::vector to a function?

What I would like to do is to call a function that contains an std::vector parameter by directly putting an array in the call. I don't want to make a vector and then pass it into the function, but I want to put the braces right in the function. Here is the general idea:

void doSomething(std::vector<int> arr)
{
    std::cout << arr[0] << std::endl;
}

int main()
{
    doSomething({ 1, 2, 3 });
}

This gives me an error. I have also tried using a lambda expression, which I am not quite familiar with, but here it is:

doSomething([]()->std::vector<int>{ return{ 1, 2, 3 }; });

This does not work. And here is specifically what I don't want:

std::vector<int> a {1, 2, 3};
doSomething(a);

So how should I approach this? I really hope that what I have written isn't completely stupid.

Upvotes: 5

Views: 2253

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You can use a temporary vector initialized from an initializer list:

 doSomething(std::vector<int>{1, 2, 3 });

Live Demo

Upvotes: 9

Related Questions