I was trying out codefights.com and noticed someones answer to a question which involved giving all the longest strings in a vector do this:
std::vector<std::string> r, allLongestStrings(std::vector<std::string> a) {
int b=0;
for (s:a) if (s.size()>b) b=s.size();
for (s:a) if (s.size()==b) r.push_back(s);
return r;
}
He's declaring a variable in the return type specifier for the function, can anyone tell me why this is allowed? I't doesn't compile on my machine and I couldn't find a gcc extension that does this, thanks in advance :).
Looking at the reference (decl-specifier-seq), I don't see how it would be possible to declare the return variable before the function name.
With C++14, you can use the
autokeyword to remove the duplicate mentioning of the return type:I fixed some other things of the code:
aas const reference, so it won't be copiedbasstd::size_tto match return type ofstd::vector::size()auto); added const reference for efficiencyLive demo.