void PrintNow(const std::vector<int> &v)
{
std::cout << v[0] << std::endl;
}
std::vector<int>().push_back(20); // this line generates no complains
PrintNow(std::vector<int>().push_back(20)); // error
From VS2010 Sp1:
eror C2664: 'PrintNow' : cannot convert parameter 1 from 'void' to 'const std::vector<_Ty> &'
Q> Is it possible that we can pass a temporary vector to function?
Use the vector<T> &arr Notation to Pass a Vector by Reference in C++ std::vector is a common way to store arrays in C++, as they provide a dynamic object with multiple built-in functions for manipulating the stored elements.
In the case of passing a vector as a parameter in any function of C++, the things are not different. We can pass a vector either by value or by reference.
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.
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