[英]How do I define a sort predicate for a templated container class in C++
最近,我的C ++有點生銹。 你們其中一位大師可以幫助我為Container類定義一個SORT謂詞,其模板參數本身就是另一類。
template <class Element>
class OrderedSequence
// Maintains a sequence of elements in
// ascending order (by "<"), allowing them to be retrieved
// in that order.
{
public:
// Constructors
OrderedSequence();
OrderedSequence(const OrderedSequence<Element>&);
// Destructor
~OrderedSequence(); // destructor
OrderedSequence<Element>& operator= (const OrderedSequence<Element>& ws);
// Get an element from a given location
const Element& get (int k) const;
// Add an element and return the location where it
// was placed.
int add (const Element& w);
bool empty() const {return data.empty();}
unsigned size() const {return data.size();}
// Search for an element, returning the position where found
// Return -1 if not found.
int find (const Element&) const;
void print () const;
bool operator== (const OrderedSequence<Element>&) const;
bool operator< (const OrderedSequence<Element>&) const;
private:
std::vector<Element> data;
};
因此,此類接收模板參數,該參數是帶有std :: string成員變量的STRUCT。
我想定義一個簡單的排序謂詞,以便在add()成員內執行:data.push_back()之后可以調用:std :: sort(data.begin(),data.end(),sort_xx)以上類的功能。
我該怎么做? 我沒有使用C ++ 11-只是普通的C ++。
模板參數Element ..轉換為:
struct AuthorInfo
{
string name;
Author* author;
AuthorInfo (string aname)
: name(aname), author (0)
{}
bool operator< (const AuthorInfo&) const;
bool operator== (const AuthorInfo&) const;
};
bool AuthorInfo::operator< (const AuthorInfo& a) const
{
return name < a.name;
}
bool AuthorInfo::operator== (const AuthorInfo& a) const
{
return name == a.name;
}
如果需要自定義謂詞,可以使用std :: find_if什么。
定義謂詞ala C ++ 03:
// For find()
struct MyPredicate
{
public:
explicit MyPredicate(const std::string name) name(name) { }
inline bool operator()(const Element & e) const { return e.name == name; }
private:
std::string name;
};
// Assuming you want to lookup in your vector<> member named "data"
std::find_if(data.begin(), data.end(), MyPredicate("Luke S."));
// To sort it, its exactly the same but with a Sort comparer as the predicate:
struct MySortComparator
{
bool operator() (const Element& a, const Element& b) const
{
return a.name < b.name;
}
};
std::sort(data.begin(), data.end(), MySortComparator());
// Or you can style sort Author without predicates if you define `operator<` in the `Element` class :
std::sort(data.begin(), data.end())
如果可以使用C ++ 11,則可以只使用lambda:
std::find_if(data.begin(), data.end(), [](const Element & e) -> bool { return e.name == "Luke S."; });
編輯:
現在,您顯示Element
我看到您已經在Author
重載了operator==
,因此您也可以這樣做:
int find (const Element& e) const
{
std::vector<Element>::iterator iter = std::find(data.begin(), data.end(), e);
return std::distance(data.begin(), iter);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.