-->

如何定义在C模板容器类排序谓词++(How do I define a sort predicate

2019-10-28 09:21发布

我的C ++是有点生疏为晚。 你大师一个可以帮助我限定了一种断言,对于一个容器类,有一个模板参数,它自身是另一个类。

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成员变量的结构体。

我想定义一个简单的排序谓词,这样我就可以拨打电话:性病::排序(data.begin(),data.end(),sort_xx)执行后:附加内data.push_back()()成员上述类的功能。

我该怎么做? 我没有使用C ++ 11 - 只是普通的老C ++。

模板参数元素..被翻译为:

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;
}

Answer 1:

什么可以使用的std :: find_if ,如果你需要一个定制的断言。

要定义谓词翼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);
}


文章来源: How do I define a sort predicate for a templated container class in C++