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

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 for a function?

+6
source share
4 answers

In C ++ 11, you can simply do:

 void PrintNow(const std::vector<int> &v) { std::cout << v[0] << std::endl; } PrintNow({20}); 

VS2010 does not yet support this part of C ++ 11. (gcc 4.4 and clang 3.1 do)

If you need only one element, then in C ++ 03 you can do:

 PrintNow(std::vector<int>(1,20)); 

If you need more than one element, I don’t think there is any single line solution. You can do it:

 { // introduce scope to limit array lifetime int arr[] = {20,1,2,3}; PrintNow(std::vector<int>(arr,arr+sizeof(arr)/sizeof(*arr)); } 

Or you can write a varargs function that takes an int list and returns a vector. If you do not use it a lot, although I do not know what it is worth it.

+9
source

The problem is that std::vector::push_back() returns void , and not that you cannot pass a temporary function.

+4
source

The error occurs because the return type of the std::vector::push_back function is void :

 void push_back ( const T& x ); 

Try the following:

 PrintNow(std::vector<int>(1, 20)); 

The above code uses one of the available constructors of the std::vector class:

 explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); 
+4
source

If all elements have the same value, you have one constructor that suits your needs:

 PrintNow(std::vector<int>(1,20)); 
+3
source

Source: https://habr.com/ru/post/913636/


All Articles