2013-06-03 41 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>());