【发布时间】:2016-04-02 03:28:37
【问题描述】:
我正在尝试通过在我自己的双向链表集合上实现 std::iterator 并尝试创建自己的 sort 函数来对其进行排序,从而更加熟悉 C++11 标准。
我希望sort 函数通过使sort 接受std::function 来接受lamba 作为排序方式,但它无法编译(我不知道如何实现move_iterator,因此返回集合的副本而不是修改传递的集合)。
template <typename _Ty, typename _By>
LinkedList<_Ty> sort(const LinkedList<_Ty>& source, std::function<bool(_By, _By)> pred)
{
LinkedList<_Ty> tmp;
while (tmp.size() != source.size())
{
_Ty suitable;
for (auto& i : source) {
if (pred(suitable, i) == true) {
suitable = i;
}
}
tmp.push_back(suitable);
}
return tmp;
}
我对函数的定义有错吗?如果我尝试调用该函数,则会收到编译错误。
LinkedList<std::string> strings{
"one",
"two",
"long string",
"the longest of them all"
};
auto sortedByLength = sort(strings, [](const std::string& a, const std::string& b){
return a.length() < b.length();
});
错误:没有函数模板“sort”的实例与参数匹配 列表参数类型为:(LinkedList, lambda []bool (const std::string &a, const std::string &)->bool)
补充资料,编译也报如下错误:
错误 1 错误 C2784: 'LinkedList<_ty> sort(const LinkedList<_ty> &,std::function)' : 不能 推导出 '
std::function<bool(_By,_By)>' 的模板参数
更新:我知道排序算法不正确并且不会做想要的事情,我无意让它保持原样,并且一旦声明正确,修复它也没有问题.
【问题讨论】:
标签: c++11 visual-studio-2013 lambda std-function