【问题标题】:C++ help with STL - sort() functionSTL 的 C++ 帮助 - sort() 函数
【发布时间】:2011-07-04 20:55:35
【问题描述】:

另一个关于STL的小问题:

我有字典:

map <string,vector <Wordy> > Dictionary;

使用结构 Wordy:

struct Wordy{ int count; string word;}

这个结构也有重载的操作符

bool operator< (Wordy& One, Wordy& Two){return One.count<Two.count;}

但是算法中的这个 sort() 函数不起作用!

sort(Dictionary.find(s)->second.begin(),Dictionary.find(s)->second.end());

【问题讨论】:

  • @Martin:OP 没有对地图进行排序,她正在对地图的特定 元素 进行排序。

标签: c++ algorithm sorting stl


【解决方案1】:

你的operator&lt; 应该通过引用到常量来获取它的参数,我想可能是这样:

bool operator< (const Wordy& One, const Wordy& Two){return One.count<Two.count;}
//              ^^^^^             ^^^^^

【讨论】:

    【解决方案2】:

    查看How to use std::sort with a vector of structures and compare function? 的帖子。它解释了如何使用自定义谓词函数进行排序

    【讨论】:

    • 我不这么认为。该问题涉及未返回 bool 的排序函数。
    • 如果可以(并且想要)实现operator&lt;,为什么还需要自定义谓词?
    • @zdan:你是说bool operator&lt;(...)函数吗?
    • @NirMH:是的,我指的是排序“谓词”而不是排序函数。
    猜你喜欢
    • 2021-06-03
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2011-08-07
    相关资源
    最近更新 更多