简体   繁体   English

对存储在双端队列中的类对象进行排序

[英]Sorting Class Objects Stored In Deque

I am trying to store email addresses written in a file and sort them by hits in the file. 我正在尝试存储写在文件中的电子邮件地址,并按文件中的点击次数对它们进行排序。

I am storing the email addresses and the number of hits in a class called emailAddress. 我将电子邮件地址和命中数存储在名为emailAddress的类中。

I am managing the members of that class in a Deque in another class called AddressManager. 我正在另一个名为AddressManager的类中的Deque中管理该类的成员。

The sort function I am trying to use is the sort from the algorithm library. 我尝试使用的排序功能是算法库中的排序。 Like this. 像这样。

[emailAddress.released() returns the number of hits. addressQueue is my emailAddress Deque]

bool AddressManager::swapTest(const emailAddress& address1, const emailAddress& address2)
{
    cout<<"Comparing: "<<address1.released()<<" to "<<address2.released()<<endl;
    return address1.released()>address2.released();
}
void AddressManager::sortAddresses()
{

    sort(addressQueue.begin(),addressQueue.end(),
        swapTest);
}

When I compile I get this error: 编译时出现此错误:

1>c:\workspace\addressmanager.cpp(36): error C3867: 'AddressManager::swapTest': function call missing argument list; use '&AddressManager::swapTest' to create a pointer to member
1>c:\workspace\addressmanager.cpp(36): error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(3639) : see declaration of 'std::sort'

Can I pass swapTest to sort, or does it need to be defined outside of AddressManager somehow? 我可以通过swapTest进行排序,还是需要以某种方式在AddressManager之外定义它? Or could someone suggest a way to implement my own sort in AddressManager and not use the library version at all? 还是有人可以建议一种方法在AddressManager中实现我自己的排序,而根本不使用库版本?

Thanks, ANkh 谢谢,ANkh

Just define an 只需定义一个

struct EmailSorter
{
  bool EmailSorter::operator ()(const emailAddress &a, const emailAddress &b) {
    return a.released()>b.released();
  }
};

EmailSorter es;

std::sort( v.begin() , v.end() , es );

and pass it to std::sort 并将其传递给std::sort

Or make swapTest a static function and do 或者将swapTest设为静态函数并执行

std::sort( v.begin() , v.end() , &AddressManager::swapTest );

Either make swapTest a static function, or use a lambda: swapTest static函数,或使用lambda:

sort(addressQueue.begin(),addressQueue.end(),
     [](const emailAddress& address1, const emailAddress& address2)
       { return address1.released() > address2.released(); }
     );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM