使用 STL/Boost/Lambda 调整映射迭代器
考虑以下非工作代码:
typedef map<int, unsigned> mymap;
mymap m;
for( int i = 1; i < 5; ++i )
m[i] = i;
// 'remove' all elements from map where .second < 3
remove_if(m.begin(), m.end(), bind2nd(less<int>(), 3));
我正在尝试从此地图中删除 .second
的元素。 3.
.这显然写得不正确。我如何使用
- 标准STL函数对象和标准STL函数对象正确编写它?使用
bind
+less<>
的技术,但无需编写自定义函子 - Boost.Bind
- C++0x Lambdas
我知道我不是erase
Consider the following non-working code:
typedef map<int, unsigned> mymap;
mymap m;
for( int i = 1; i < 5; ++i )
m[i] = i;
// 'remove' all elements from map where .second < 3
remove_if(m.begin(), m.end(), bind2nd(less<int>(), 3));
I'm trying to remove elements from this map where .second < 3
. This obviously isn't written correctly. How do I write this correctly using:
- Standard STL function objects & techniques using
bind
+less<>
but without having to write a custom functor - Boost.Bind
- C++0x Lambdas
I know I'm not erase
ing the elements. Don't worry about that; I'm just simplifying the problem to solve.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定如何仅使用 STL 绑定器来执行此操作,但我认为您的主要问题是传递给您提供给
remove
的函子的内容不仅仅是一个int 而是一个
对
。使用 boost::bind 你会这样做:
使用 lambda 函数,它是这样的:
抱歉,我还没有检查它是否可以编译。
I'm not sure how to do this using just the STL binders but I think your main problem is that what's being passed into the functor you give to
remove
isn't just anint
but apair<int, unsigned>
.Using boost::bind you'd do it like this:
Using a lambda function it's something like this:
I haven't checked that this compiles, sorry.
remove_if
不适用于关联容器。但是remove_copy_if
可能会起作用,但代价是复制地图。相反,我将使用count_if
来完成此操作。1)标准STL函数对象&使用bind + less的技术但无需编写自定义函子
2) Boost.Bind
3) C++0x Lambda
如果您确实想要remove_if 行为,则需要推出自己的算法。我不相信有任何可修改的标准算法适用于关联容器。
remove_if
will not work with associative containers. Butremove_copy_if
may work but at the expense of copying your map. Instead I'll do it withcount_if
.1) Standard STL function objects & techniques using bind + less<> but without having to write a custom functor
2) Boost.Bind
3) C++0x Lambdas
If you really want remove_if behavior you'll need to roll your own algorithm. I don't believe there are any modifying standard algorithms that work with associative containers.
尽管由于上述原因我无法使用
remove_if
算法,但我使用了count_if
算法来处理一些复杂的函子定义和组合。这些并未在标准中定义,但它们的灵感来自于 SGI STL。Although I could not get the
remove_if
algorithm to work for the reasons mentioned above, I gotcount_if
algorithm to work with somewhat elaborate functor definitions and compositions. These are not defined in the standard but they are inspired from what is available in SGI STL.