vector高效删除

vector高效删除

1、使用erase:每次删除都要移动后面的元素

2、使用remove_if

3、stable_partition

4、运行时间比:630:1:2.5

#include <iostream>
#include <algorithm>
#include<vector>
#include<ctime>
#include<iterator>

using namespace std;

bool pass(double x) {
	return x >= 60;
}
bool fail(double x) {
	return x < 60;
}
int main()
{
	vector<double> grades, grades_tmp, grades_tmp2;
	vector<double>::iterator iter;
	clock_t start, end;
	for (int i = 0; i < 100000; i++) {
		grades.push_back(rand() % 100);
	}
	grades_tmp.assign(grades.begin(), grades.end());
	grades_tmp2.assign(grades.begin(), grades.end());


	start = clock();
	iter = grades.begin();
	while (iter != grades.end()) {
		if (pass(*iter))iter++;
		else {
			iter = grades.erase(iter);
		}
	}
	end = clock();
	cout << "erase time is:" << double(end - start) << endl;


	vector<double>::iterator it2;
	start = clock();
	it2 = remove_if(grades_tmp.begin(), grades_tmp.end(), fail);
	grades_tmp.erase(it2, grades_tmp.end());
	end = clock();
	/*for (auto it3 = grades_tmp.begin(); it3 != it2; it3++) {
		cout << *it3 << " ";
	}*/
	cout << "erase time is:" << double(end - start) << endl;


	start = clock();
	it2 = stable_partition(grades_tmp2.begin(), grades_tmp2.end(), pass);
	end = clock();
	/*for (auto it3 = grades_tmp2.begin(); it3 != it2; it3++) {
		cout << *it3 << " ";
	}*/
	grades_tmp2.erase(it2, grades_tmp2.end());
	cout << "erase time is:" << double(end - start) << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值