Effective_STL 学习笔记(四十七) 避免产生只写代码

假设有一个 vector<int>,想要去掉 vector 中的值小于 x 而出现在至少和 y 一样大的最后一个元素之后的所有元素

1   vector<int> v;
2   int x, y;
3   . . .
4   v.erase( remove_if( find_if( v.begin(), v.end(), 
5           bind2nd(greater_equal<int>(), y) ).base(),   // 找到比 y 大的位置
6           v.end(), bind2nd(less<int>(), x) ), v.end() );

可以使用的方法:

1   typedef vector<int>::iterator VecIntIter;
2   VecIntIter rangeBegin = find_if( v.rbegin(), v.rend(), 
3             bind2nd( greater_equal<int>(), y ) ).base();
4   v.erase( remove( rangeBegin, v.end(), 
5             bind2nd( less<int>(), x ) ), v.end() );

找到 vector 中一个值最后一次出现需要用逆向迭代器调用 find 或 find_if 的某种形式

去掉元素需要使用 erase 或 erase-remove 惯用法

1   v.erase( remove_if( find_if( v.rbegin(), v.rend(), something ).base(),
2                  v.end(), something ), v.end() );

猜你喜欢

转载自www.cnblogs.com/kidycharon/p/10055401.html
今日推荐