gpt4 book ai didi

c++ - 按私有(private)成员对自定义对象进行排序

转载 作者:行者123 更新时间:2023-11-28 06:17:00 25 4
gpt4 key购买 nike

我找到了很多关于排序函数的解释,但我无法用我的代码实现一个。

我有这样的结构:

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

我在类型兼容性或隐私方面遇到了一些问题。也许那是因为我正试图将这个私有(private)成员从类(class)中剔除......谢谢

编辑:我做到了\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>());

感谢您对 map 的解释

最佳答案

因为你的内部类只有一个字段并且它有一个 getter(你可能想让这个 getter 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++ - 按私有(private)成员对自定义对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com