2010-12-21 105 views
3

这里是我的地图:HowTo sort std :: map?

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

问题:如何通过第二个值的关键参数(排序std::mapmarket_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

还有several options gamedev.net。查看Fruny发布的帖子。

另外:为什么你不认为升压作为一个可能的解决方案提供商?这是一个备受尊敬的,经过同行评估的,专业C++编码人员有据可查的解决方案。

+0

STL必须完成这项工作,我想。 PS。除了额外的包括 - 没办法。谢谢! – mosg 2010-12-21 15:56:00

+0

谢谢,托尼,这个链接解决了我的问题!顺便说一句,我用google搜索和live tab打开链接,然后开始在SO上发布我的问题......我将`std :: map`插入到`std :: vector`并完全排序那个婊子! - WoW:D – mosg 2010-12-21 16:47:30

1

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

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