2013-06-03 45 views
1

我有一个列表容器类(不是std::list),可以存储任何 类型。我想在此容器中存储许多std::listS,其中 不同类型(list<int>list<string>等)。std :: list.sort(),二元谓词?

我可以在排序时使用通用二元谓词吗?

伪代码:

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试过了 - 工作正常。

回答

2

是,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>());