【问题标题】:Custom sorting in ordered container在有序容器中自定义排序
【发布时间】:2015-03-10 09:27:53
【问题描述】:

我有一个带有对象的有序容器(通常是 std::vector

  1. Banana
  2. Apple
  3. Peach

及以上自定义订单。现在对象经过一些处理,可能已从容器中移除并重新插入,从而产生一个新的有序容器。

我已经存储了订单(Banana -> 1, Apple -> 2, Peach -> 3 ) 并希望在新订购的容器中重新建立特定的自定义订单。

此时对象已经存在(即我不能简单地按所需顺序插入)。

因此,与其用我自己的一些天真的算法过度交换,我想知道标准库中是否有一些算法我可以巧妙地使用..?

【问题讨论】:

  • 为什么不将对象留在容器中并复制出容器呢? vector 返回一个您可以处理的引用。
  • 您是否正在寻找类似std::sort(fruits.begin(), fruits.end(), [](const std::string& a, const std::string& b) { return rank[a] < rank[b]; }); 的东西,其中rankstd::map<std::string, int> 保存您的字符串到排名的映射?
  • @IgorTandetnik 干杯 - 完成了这项工作..我自己也可以想到的..

标签: c++ c++11 vector standard-library


【解决方案1】:

嗯,伊戈尔写的东西几乎可以完成这项工作..

std::sort(fruits.begin(), fruits.end(), 
          [&](const std::string& a, const std::string& b) 
          { return rank[a] < rank[b]; } ); 

其中 rank 是 std::map&lt;std::string, int&gt; 持有字符串到排名的映射

【讨论】:

    【解决方案2】:

    std::sort 在标准库中,它非常狡猾!它可以按默认的

    http://www.cplusplus.com/reference/algorithm/sort/?kw=sort

    【讨论】:

    • (哦,伊戈尔打败了我!)
    • 我认为问题是,该运算符中应该包含什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2016-05-07
    • 2011-11-01
    • 2013-11-04
    相关资源
    最近更新 更多