I have a code in C++14. However, when I used it in C++11, it has an error at const auto
. How to use it in C++11?
vector<vector <int> > P;
std::vector<double> f;
vector< pair<double, vector<int> > > X;
for (int i=0;i<N;i++)
X.push_back(make_pair(f[i],P[i]));
////Sorting fitness descending order
stable_sort(X.rbegin(), X.rend());
std::stable_sort(X.rbegin(), X.rend(),
[](const auto&lhs, const auto& rhs) { return lhs.first < rhs.first; });
const auto
is not supported in C++11 as a lambda parameter (actually generic lambdas are not supported in C++11).To fix:
I know there is an accepted answer, but you can also use
decltype
in C++11 for this, it looks a bit messy...Use
cbegin()
here as you get the const correctvalue_type
of the container.Alternatively you can directly use the
value_type
typedef of the container with adecltype
, likeUnfortunately, generic lambdas that take
auto
(whetherconst
or not) is a C++14 only feature.See here https://isocpp.org/wiki/faq/cpp14-language#generic-lambdas for some more details.
C++11 doesn't support generic lambdas. That's what
auto
in the lambda's parameter list actually stands for: a generic parameter, comparable to parameters in a function template. (Note that theconst
isn't the problem here.)You have basically two options:
Type out the correct type instead of
auto
. Here it is the element type ofX
, which ispair<double, vector<int>>
. If you find this unreadable, a typedef can help.Replace the lambda with a functor which has a call operator template. That's how generic lambdas are basically implemented behind the scene. The lambda is very generic, so consider putting it in some global utility header. (However do not
using namespace std;
but type outstd::
in case you put it in a header.)