简体   繁体   English

C ++:使用boost lambda在std :: tr1 :: unordered_map中获取最大值

[英]C++: Using boost lambda to get maximum values in a std::tr1::unordered_map

I have a std::tr1::unordered_map<int, A> map; 我有一个std::tr1::unordered_map<int, A> map; where A is a class with a member variable (int x). 其中A是具有成员变量(int x)的类。

I would like to find the key i in map such that map[i].x is maximum. 我想在map中找到键i,以使map [i] .x最大。

I know that I can write a functor to go with std::max_element. 我知道我可以编写一个函子来与std :: max_element一起使用。 How do I do this instead, using boost lambda (I am trying to learn it) ? 我如何使用boost lambda来做到这一点(我正在尝试学习)? I do not have C++0x. 我没有C ++ 0x。

As an added question, what if I had class A defined as below: 另外一个问题是,如果我的A类定义如下:

class A { int x; A类{int x; int y; 诠释 }; };

And I wanted to find the maximum wrt x (if that maximum was 0, find the maximum wrt to y). 我想找到最大wrt x(如果最大为0,则将最大wrt设为y)。 Again, one solution would be to iterate over the tuples of the map (keeping both maxima in memory). 同样,一种解决方案是遍历映射的元组(将两个最大值保留在内存中)。 Is there a way to modify max_element to do this ? 有没有办法修改max_element来做到这一点?

boost.lambda uses boost.bind to access member variables. boost.lambda使用boost.bind访问成员变量。 It comes up a bit wordy: 它有点罗word:

typedef std::tr1::unordered_map<int, A> map_t;
map_t m;

A max_a = std::max_element(m.begin(), m.end(),
                bind(&A::x, bind(&map_t::value_type::second, _1))
              < bind(&A::x, bind(&map_t::value_type::second, _2))
         )->second;

test: https://ideone.com/V6SZL 测试: https//ideone.com/V6SZL

You may save half the headache with boost.range 您可以使用boost.range减轻一半的头痛

A max_a = *boost::max_element(m | map_values, bind(&A::x, _1) < bind(&A::x, _2));

But in practice, I think, a functor would be best. 但我认为在实践中,最好使用函子。

Since you're just starting to learn Boost.Lambda, now is the perfect time to forget it exists and learn Boost.Phoenix instead. 由于您刚刚开始学习Boost.Lambda,因此现在是忘记它存在而学习Boost.Phoenix的完美时机。 Boost.Phoenix is the replacement for Boost.Lambda and is considerably more powerful, and often more succinct: Boost.Phoenix是替代Boost.Lambda是强大多,而且往往更简洁:

typedef std::tr1::unordered_map<int, A> map_t;
map_t m;

int i = std::max_element(
    m.begin(),
    m.end(),
    bind(&A::x, at_c<1>(_1)) < bind(&A::x, at_c<1>(_2))
)->first;
A& max_a = m[i];

Note that Boost.Phoenix v2 is currently a sublibrary of Boost.Spirit , but in 1.47.0 Boost.Phoenix v3 is slated to be released as a proper standalone Boost library. 请注意,Boost.Phoenix v2当前是Boost.Spirit的子 ,但是在1.47.0中,Boost.Phoenix v3计划作为适当的独立Boost库发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM