如何对 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::map
进行排序(通过 market_value_
,让它为 int)?示例或链接?
附言。 Boost方法不感兴趣!
聚苯硫醚。我无法使用比较函子初始化我的 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;
其中 _Entry
是 PositionMonth
std::vector<data_t> vec(item.funds_end_.begin(), item.funds_end_.end());
std::sort(vec.begin(), vec.end(), Nav::LessSecondCcy<data_t>());
完成!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
gamedev.net 有几个选项。往下看弗鲁尼 (Fruny) 的帖子。
旁白:您为什么不考虑将 Boost 作为可能的解决方案提供商?对于专业 C++ 编码人员来说,这是一个受人尊敬、经过同行评估、文档齐全的解决方案。
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.
也许是 std::map 构造函数上 cplusplus.com 文章中的示例代码给出您正在寻找的说明!
编辑:上面链接的示例代码中实例化的
第五
映射向您展示了如何更改比较器对象。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.