如何对std::map进行排序?

3

这是我的地图:

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

问题: 如何按照第二个值键参数(即 market_value_,假设为整数)对 std::map 进行排序?有示例或链接吗?

附注:不感兴趣的 Boost 方法!

附注2:我无法使用比较函数初始化我的 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个回答

2

几个选项gamedev.net。向下滚动线程,找到Fruny的帖子。

另外:为什么不考虑Boost作为可能的解决方案提供者?它是一个备受尊重、同行评估、文档完善的专业C++编码人员解决方案。


STL应该能够完成这项工作,我猜。另外除了额外的包含文件 - 没有其他办法。谢谢! - mosg
谢谢,Tony,这个链接解决了我的问题!顺便说一下,当我开始在SO上发布问题时,我已经使用谷歌搜索并打开了精确的该链接。我将 std::map 插入到 std::vector 中,并完全排序那只母狗!- WoW :D - mosg

1
也许cplusplus.com上std::map构造函数的示例代码可以给你所需要的澄清! 编辑:上面链接中示例代码中实例化的第fifth个map向你展示了如何更改比较器对象。

从示例代码中可以看出,'fourth'和'fifth'是使用显式默认构造函数构建的。'fifth'指定了比较器对象,而假定分配器使用默认值。因此,'fourth'和'fifth'都没有填充任何对象。 - yasouser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接