0

我的 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;
}
4

1 回答 1

0

如果您需要自定义谓词,可以使用什么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我看到你已经超载operator==Author,所以你也可以这样做:

int find (const Element& e) const
{
  std::vector<Element>::iterator iter = std::find(data.begin(), data.end(), e);
  return std::distance(data.begin(), iter);
}
于 2014-06-11T23:51:43.670 回答