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:
auto retVec()
before deduction of auto
--->
auto ret_vec = retVec(**)**;
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.
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.
Vectors as return valuesYes, functions in C++ can return a value of type std::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.
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.
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 itsreturn
statement using the rules for template argument deduction.
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).
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