通过私人成员对自定义对象进行排序

Sorting custom object by private members

本文关键字:对象 排序 自定义 成员      更新时间:2023-10-16

我找到了许多关于排序功能的解释,但是我无法用代码实现一个。

我有这样的结构:

class Out{
  public:
     const std::map<std::string,In>& getListIn()const;
  private:
     std::map<std::string,In> listIn;
     class In{
        public:
           const float& getScore();
        private :
              float score;
     };
};

我想按得分(最高到最小)对listIn进行排序。我尝试超载operator>或创建自己的功能:

 std::map<std::string,Out::In> notVisited = listIn;
 bool Out::In::compareCostScore (const std::pair<std::string,Out::In>& v1,const std::pair<std::string,Out::In>& v2){
        return (v1.second.getCostScore() > v2.second.getCostScore());
 }
 std::sort(notVisited.begin(), notVisited.end(), Out::In::compareCostScore());

但是该功能尚不清楚。或:

std::sort(notVisited.begin(), notVisited.end(),[] (const std::map<std::string,Out::In>& v1, const std::map<std::string,Out::In>& v2) {return (v1.second.getCostScore() < v2.second.getCostScore()};)

我在类型或隐私的兼容性方面遇到了一些问题。也许是因为我试图将这个私人成员从班级中分类出来...谢谢

编辑:我做到了 o/:

bool operator > (const In& v) const{
                return (score > v.score);
}
std::vector<Out::In> notVisited;
for( std::map<std::string,Out::In>::iterator it = listIn.begin(); it != listIn.end(); ++it ) {
    notVisited.push_back( it->second );
}
std::sort(notVisited.begin(), notVisited.end(), std::greater<Out::In>());

感谢您有关地图的阐述

,因为您的内部类只有一个字段,并且它具有一个getter(您可能需要制作此GETER const const float& getScore() const),您可以简单地将Out::in声明更改为public并摆脱问题。但是,如果它是提取物,并且在Out::in之后有更多的逻辑,那么您要隐藏在公共访问中,则可以将比较器定义为这样的朋友函数:

class Out{
/* ... */
public:
    friend bool Out::In::compareCostScore (const std::pair<std::string,Out::In>& v1,const std::pair<std::string,Out::In>& v2);
}