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?
In C++11 you can just do:
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:
If you need more than one element then I don’t think there’s any one line solution. You could do this:
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.