通过私人成员对自定义对象进行排序
Sorting custom object by private members
我找到了许多关于排序功能的解释,但是我无法用代码实现一个。
我有这样的结构:
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);
}
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 对象接收堆栈溢出异常 c++ 的排序向量
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 排序谓词没有传递对索引对象的引用?
- 使用指针指向对象C++对向量进行排序
- 按类成员的顺序对包含类对象的C++向量进行排序
- 无法使用接口类型对priority_queue中的对象进行排序<T>
- 基于不同字段的对象向量的排序功能
- 基于3个对象的自定义排序
- 尝试使用比较运算符对对象向量进行排序
- C++排序的对象集
- 从文件中读取并将其内容放入对象数组中,然后对它们进行排序
- q排序类对象的列表
- std::atexit 从全局对象的构造函数调用时的排序
- 尝试对对象数组进行排序时程序终止
- std::排序为排序自定义对象时出现的向量引发错误
- 通过其char键对对象指针的C 向量进行排序
- 排序算法,使用模板按内部数据对对象进行排序
- 在对象向量中的对象字段排序
- 如何使用 std::sort 对数组中的特定对象进行排序