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.
If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.
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.
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.
You can use a temporary vector initialized from an initializer list:
doSomething(std::vector<int>{1, 2, 3 });
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With