[英]std::list.sort(), binary predicate?
我有一个列表容器类(不是std::list
)可以存储任何类型。 我想在此容器中以不同的类型( list<int>
, list<string>
等)存储许多std::listS
。
在对它们进行排序时,可以使用通用二进制谓词吗?
伪代码:
template <typename T>
bool compare(const T& input1, const T& input2)
{
return input1>input2;
}
for(auto i = myList.begin(); i!=myList.end(); ++i) //i is an iterator to a std::list
{
(*i).sort(compare<decltype(*i)::value_type>);
//when dereferencing i I get a
//std::list
}
这是否有效(我不确定是否可以使用decltype这样)?
问题是我什至无法编译这个简单的例子:
#include <iostream>
#include <list>
using namespace std;
template <typename T>
void display(const T& input)
{
for(auto i = input.cbegin(); i!=input.cend(); ++i)
cout << *i << ' ';
cout << endl;
return;
}
template <typename R>
class SomeFunc
{
public:
bool operator ()(const R& in1, const R& in2)
{
return in1>in2;
}
};
template <typename R>
bool someFunc(const R& in1, const R& in2)
{
return in1<in2;
}
int main()
{
list<int> myList;
myList.push_back(5);
myList.push_back(137);
myList.push_back(-77);
display(myList);
myList.sort(SomeFunc<decltype(myList)::value_type>());
display(myList);
myList.sort(someFunc<decltype(myList)::value_type>);
display(myList);
cin.ignore();
return 0;
};
更正:它的确在这里编译: http ://ideone.com/ZMcjSJ虽然不是在我的VS2012上,但我开始讨厌VS。 谁能说清楚为什么无法在VS2012上编译的可能原因? 我显然在VS2012中有decltype命令,但我想它不像C ++ 11 dectype那样起作用? http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx
我在CodeBlocks中尝试了将gnu gcc设置为C ++ 11-正常工作。
是的,方法std::list<T>::sort()
有一个需要比较函子的重载:
template <typename T>
struct MyComparator
{
bool operator() const (const T& input1, const T& input2)
{
return input1 > input2;
}
};
...
myList.sort(MyComparator<T>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.