HowTo sort std::map?

99封情书 提交于 2019-12-09 03:38:36

问题


Here is my map:

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

where PositionMonth is a structure, ex.:

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

Question: how to sort std::map by second value key param (by market_value_, let it be int)? Examples or links?

PS. Boost methods not interested!

PPS. I'm unable to initialise my std::map with compare functor!

Thanks for help!


My solution (or how I did it myself):

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

and in function:

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

where _Entry is PositionMonth

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

Done!


回答1:


There are several options gamedev.net. Look down the thread for the posting by Fruny.

Aside: Why would you not consider Boost as a possible solution provider? It's a respected, peer evaluated, well documented solution for professional C++ coders.




回答2:


Maybe the example code in the cplusplus.com artile on std::map constructor give the clarification you are looking for!

EDIT: The fifth map instantiated in the example code in the link above shows you how to change the comparator object.



来源:https://stackoverflow.com/questions/4500962/howto-sort-stdmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!