如何排序std :: map?

时间:2010-12-21 15:36:19

标签: stl functor

这是我的地图:

typedef std::map<int/*security id*/, PositionMonth> PortfolioMonth;

其中PositionMonth是一个结构,例如:

struct PositionMonth
        {
            Nav::Shares shares_;
            Nav::Amount market_value_;

            PositionMonth(void)
                {}
            PositionMonth(const Nav::Amount& market_value
                    , const Nav::Shares& shares)
                : market_value_(market_value)
                , shares_(shares)
                {}
        };

问题:如何按第二个值键param(std::map排序market_value_,让它为int)?示例或链接?

PS。提升方法不感兴趣!

PPS。我无法用比较函数初始化我的std :: map!

感谢您的帮助!


我的解决方案(或我自己如何做到):

template<class T>
    struct LessSecondCcy
        : std::binary_function<T,T,bool>
    {
        inline bool operator ()(const T& _left, const T& _right)
        {
            return _left.second.market_value_.currency() < _right.second.market_value_.currency();
        }
    };

并且在功能中:

typedef std::pair<int/*security id*/, _Entry> data_t;

其中_EntryPositionMonth

std::vector<data_t> vec(item.funds_end_.begin(), item.funds_end_.end());
std::sort(vec.begin(), vec.end(), Nav::LessSecondCcy<data_t>());

完成!

2 个答案:

答案 0 :(得分:2)

several options gamedev.net。仔细查看Fruny发布的帖子。

除此之外:您为什么不将Boost视为可能的解决方案提供商?对于专业的C ++编码人员来说,这是一个备受尊重,同行评估,记录良好的解决方案。

答案 1 :(得分:1)

也许std :: map构造函数中cplusplus.com artile中的示例代码给出了您要查找的说明!

编辑:上面链接示例代码中实例化的fifth地图显示了如何更改比较器对象。

相关问题