Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return vector as auto from function

Tags:

c++

c++11

angular

Is it possible to return std::vector as auto? For example:

auto retVec() {
  std::vector<int> vec_l;

  l.push_back(1);
  l.push_back(2);

  return vec_l;
}
...
auto ret_vec = retVec();
for (auto& it : ret_vec) {
}

when I write something like this I get an error:

  1. error: use of auto retVec() before deduction of auto ---> auto ret_vec = retVec(**)**;
  2. error: unable to deduce auto&& from ret_vec ---> for (auto it : **ret_vec**) {

How do I actually write this?

UPDATE: I'm sorry. I use this retVec as method in class and it doesn't work. When I use it as function in class - everything work fine. My mistake in formulating the question.

like image 734
Max Avatar asked Sep 20 '18 12:09

Max


People also ask

Can you return a vector from a function?

A function can return a vector by its normal name. A function can return a vector literal (initializer_list), to be received by a normal vector (name). A vector can return a vector reference, to be received by a vector pointer. A vector can return a vector pointer, still to be received by another vector pointer.

Can return type be a vector?

Vectors as return valuesYes, functions in C++ can return a value of type std::vector .

How do you write a return vector?

Use the vector<T> func() Notation to Return Vector From a Function. The return by value is the preferred method if we return a vector variable declared in the function. The efficiency of this method comes from its move-semantics.

How do I return a new vector in C++?

In C++11, this is the preferred way: std::vector<X> f(); That is, return by value. With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.


2 Answers

You are compiling for the C++11 standard. You need to compile for at least the C++14 standard as the deduced return type is only available starting with C++14. The reference states:

In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.

like image 194
Ron Avatar answered Oct 20 '22 22:10

Ron


You can see this error on Coliru when compiling with -std=c++11, but this works as intended when compiled with -std=c++14.

Note that gcc even outputs a hint at this:

main.cpp:8:13: note: deduced return type only available with -std=c++14 or -std=gnu++14

Deducted return type using auto is indeed a C++14 feature, see Item (3).

like image 45
JBL Avatar answered Oct 20 '22 21:10

JBL