Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create temporary pass-in `std::vector<int>` parameter?

Tags:

c++

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?

like image 633
q0987 Avatar asked Apr 19 '12 14:04

q0987


People also ask

How do you pass a vector call by reference?

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.

Can you pass vector by value?

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.


1 Answers

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.

like image 108
bames53 Avatar answered Oct 19 '22 16:10

bames53