Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 468
Archie Gertsman Avatar asked Mar 04 '16 23:03

Archie Gertsman


People also ask

How do you pass rvalue reference to a function?

If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.

How do you pass a vector by value?

A vector<int> is not same as int[] (to the compiler). vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor. So, you must use vector<int>& (preferably with const , if function isn't modifying it) to pass it as a reference.

How do you pass a vector call by reference in C++?

If you define your function to take argument of std::vector<int>& arr and integer value, then you can use push_back inside that function: Show activity on this post. Pass by reference has been simplified to use the & in C++. Show activity on this post.


1 Answers

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

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

Live Demo

like image 86
πάντα ῥεῖ Avatar answered Oct 03 '22 01:10

πάντα ῥεῖ