I can't understand how can I use lambda with generic arguments and pass it as parameter in another method.
Below my code that I have now (wrong, of course):
class Arrays final
{
public:
template<class RandomIt>
static void InsertionSort(RandomIt first, RandomIt last) {
auto func = [](RandomIt lt, RandomIt rt) {
return *lt > (*rt);
};
InsertSort(first, last, func);
}
template<class RandomIt>
static void InsertionSortDesc(RandomIt first, RandomIt last) {
auto func = [](RandomIt lt, RandomIt rt) {
return *lt < (*rt);
};
InsertSort(first, last, func);
}
private:
Arrays();
template<class RandomIt>
static void InsertSort(RandomIt first, RandomIt last,
std::function<bool (RandomIt, RandomIt)> func) {
int length = std::distance(first, last);
if (length < 2) {
return;
}
RandomIt j = first + 1;
for (; j != last; ++j) {
auto key = *j;
RandomIt i = j - 1;
while (i >= first && func(i, j)) {
*(i + 1) = (*i);
--i;
}
*(++i) = key;
}
}
};
It crashes in the compile time with errors:
arrays.h:38: error: no matching function for call to 'Arrays::InsertSort(const int*&, const int*&, Arrays::InsertionSort(RandomIt, RandomIt) [with RandomIt = const int*]::<lambda(const int*, const int*)>&)'
InsertSort(first, last, func);
^
How to write it correctly? Is it possible in C++ v11?
InsertSortto betemplate <class RandomIt, class Compare> static void InsertSort(RandomIt first, RandomIt last, Compare && func) { .... There is no reason to require the argument to be anstd::functioninstance; any suitable callable should do.arrays.h:67: ошибка: assignment of read-only location '*(i + 4u)' *(i + 1) = (*i); ^const int *(pointer to constant int), so what did you expect? Show the code where you callArrays::InsertionSort().