请大家帮看看 C ++ STL remove_if() 函数感觉没用错,为什么得不到想要的结果

C++语言 码拜 8年前 (2016-09-23) 877次浏览
上一段代码,本人本意是先移除大于5的元素但是结果貌似没变化,:

#include<iostream>
#include<algorithm>
#include<list>
#include<vector>
#include<list>
#include<functional>
bool func(int n)
	{
	return n > 5;
	}
int main()
{
	using namespace std;
	list<int> li = { 1,2,3,4,5,6,7,7,8,9 };
	for (auto x : li)
		cout << x << "  ";
	cout<< endl;
	remove_if(li.begin(),li.end(), func);
	for (auto x : li)
		cout << x << "  ";
	system("pause");
	return 0;
}

得出结果:
请大家帮看看 C ++ STL remove_if() 函数感觉没用错,为什么得不到想要的结果
该函数原型:

template<class _FwdIt,
	class _Pr> inline
	_FwdIt remove_if(_FwdIt _First, _FwdIt _Last _Pr _Pred)//   Pred是谓词没错啊,为什么结果不是本人要的??
	{	// remove each satisfying _Pred
	_DEBUG_RANGE(_First, _Last);
	return (_Rechecked(_First,
		_Remove_if_unchecked(_Unchecked(_First), _Unchecked(_Last), _Pred)));
	}

请大家帮看看,为什么?

解决方案

15

请注意它的返回值
remove 系列函数通常与容器的 erase 函数并用,称为 Erase–remove idiom
所以你的代码应该是

li.erase(remove_if(li.begin(),li.end(), func), li.end());

5

用错了。具体问题在哪可以搜索一下 erase-remove idiom
既然已经用了 list ,可以直接用 list 的成员函数 remove_if ,效率更高(原因是不需要做移动操作)

li.remove_if(func);

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明请大家帮看看 C ++ STL remove_if() 函数感觉没用错,为什么得不到想要的结果
喜欢 (0)
[1034331897@qq.com]
分享 (0)