我的 C++ 最近有点生疏了。你们中的一位大师可以帮我为容器类定义一个 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;
}