一道关于STL list笔试题,删除指定下标的元素

今天同学参加一家公司的在线测试,有一道题目,让我做做,很基础,但是花了点时间,唉,技术真心不行。

已知一个整数列表保存着一系列随机整数,请编写一个函数批量删除指定序号的项(序号从0开始)。

如列表初始值为: {1, 45, 23, 67, 9, 12, 24}
输入要删除的序号: {1, 5, 3}

执行后的结果:{1, 23, 9, 24}

题目并不难,最开始思路比较窄,对list的用法不是很熟,拿到题目第一时间就想着用本办法解决,构造了一个新的list然后将不会被删除的元素都插入这个list,然后调用swap函数。这方法被弊了。

然后,想到一种方法,就是将要删除的list中的元素下标排序,从最小的下标开始删除,每次删除操作都计数CNT,后都将下一次要操作的下标减去这个CNT(因为前面的删除操作使得list的元素个数减少,相应地实际下标也减小了)。代码相对比较简洁,也考虑到下标越界的问题。

#include<list>
#include<algorithm>
#include<iostream>
using namespace std;

void deleteItems(list<int>&items, list<int>& delIds)
{
	delIds.sort();
	int cnt = 0;
	for (list<int>::iterator itor = delIds.begin(); itor != delIds.end(); itor++)
	{
		if (*itor >= items.size())
		{
			break;
		}

		list<int>::iterator itemItor = items.begin();
		for (size_t i = 0; i < (*itor - cnt); i++)
		{
			itemItor++;
		}
		items.erase(itemItor);
		cnt++;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	list<int> items;
	items.push_back(1);
	items.push_back(45);
	items.push_back(23);
	items.push_back(67);
	items.push_back(9);
	items.push_back(12);
	items.push_back(24);
	for (list<int>::iterator itr = items.begin(); itr != items.end(); itr++)
	{
		cout << *itr << " ";
	}

	cout << endl;
	list<int> delIds;
	delIds.push_back(1);
	delIds.push_back(5);
	delIds.push_back(3);
	delIds.push_back(9);
	delIds.push_back(10);

	deleteItems(items, delIds);

	cout << "result: ";
	for (list<int>::iterator itr = items.begin(); itr != items.end(); itr++)
	{
		cout << *itr << " ";
	}
	cout << endl;

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值