删除数组中指定的元素

问题描述

使用C++实现数组中指定元素的删除。

#include <iostream>
#include <vector>
using namespace std;

int removeElement(vector<int> & list, int target);
ostream & operator<<(ostream & os, const vector<int> & list);

int main() {
	vector<int> list = {1,2,3,2,2,3,6,2,7};
	int slow = removeElement(list, 2);
	for (int i = slow; i < list.size(); ++i)
		list[i] = 0;
	cout << slow << endl;
	cout << list;
	return 0;
}

int removeElement(vector<int> & list, int target) {
	int fast = 0;
	int slow = 0;

	while (fast < list.size()) {
		if (list[fast] != target) {
			list[slow] = list[fast];
			slow++;
		}
		fast++;
	}
	return slow;
}

ostream & operator<<(ostream & os ,const vector<int> & list) {
	int i = 0;
	cout << "{";
	for (i = 0; i < list.size() - 1; ++i) {
		cout << list[i] << ", ";
	}
	cout << list[i];
	cout << "}" << endl;
	return os;
}

代码分析:

首先,我们定义两个指针fast和slow,当fast指针指向的元素不等于目标元素时,便将fast指向元素的值赋值给slow指针指向的值,此时slow和fast向后移动一位。这样,当slow指向target时,target便被其后面的值覆盖,便实现了指定元素的删除。最后的slow表示删除指定元素后数组的元素个数(以0为初始值),如果我们将slow以后的元素全部赋值为0,便实现了删除指定元素后数组的前移(以0补充)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wind_freedom

觉得写的不错就鼓励一下小编吧~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值