批量前移list中指定的元素

批量选中list列表中的元素,进行移位,可用于批量选中图层进行上下移动的操作。

//将list中指定的元素向前移动一位(由lstMove指定);
void moveItem(const std::list<int>& lstMove, std::list<int>& lstAll)
{
	if (lstMove.empty()) return;


	std::list<int>::const_iterator _lstMoveBegin = lstMove.begin();
	std::list<int>::const_iterator _lstMoveEnd = lstMove.end();


	//记录已处理的元素个数;
	int iCount = 0;
	int iSum = lstMove.size();


	//指定元素在队首的无需移位;
	std::list<int>::iterator itr = lstAll.begin();
	for (;itr != lstAll.end();++itr)
	{
		if(_lstMoveEnd == std::find(_lstMoveBegin, _lstMoveEnd, *itr)) break;
		if(++iCount == iSum) return;
	}


	//处理需要移位的元素;
	//此时迭代器itr为第一个非指定元素;
	std::list<int>::iterator itrMove = itr;
	std::list<int>::iterator itrNext = ++itr;


	for (;itrNext != lstAll.end(); itrMove = itrNext++)
	{
		if(_lstMoveEnd == std::find(_lstMoveBegin, _lstMoveEnd, *itrNext)) continue;


		//交换元素值(迭代器不改变);
		std::swap(*itrMove, *itrNext);
		if(++iCount == iSum) return;
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在C++删除数组指定元素,可以使用双指针的方法。首先,我们定义两个指针i和j,初始时都指向数组的开头。然后,我们遍历数组,当遇到目标元素时,将指针j前移一位,跳过目标元素。当遇到非目标元素时,将该元素复制到指针j的位置,并将指针j后移一位。最后,返回指针j的值,即为删除目标元素后的数组长度。 以下是删除数组指定元素的C++代码示例: ``` #include <iostream> #include <vector> using namespace std; int removeElement(vector<int>& nums, int val) { int length = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i != val) { nums[length = nums[i]; length++; } } return length; } int main() { vector<int> nums = {0, 1, 2, 2, 3, 0, 4, 2}; int val = 2; int length = removeElement(nums, val); cout << length << endl; for (int i = 0; i < length; i++) { cout << nums[i << endl; } return 0; } ``` 这段代码首先定义了一个函数`removeElement`来删除数组指定元素。然后,在`main`函数调用该函数,并打印删除指定元素后的数组长度以及数组的内容。 请注意,这段代码使用了`vector`容器来存储数组,因为`vector`可以动态调整大小。如果想直接使用普通数组,请根据引用提供的C代码进行修改。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [C++:移除数组指定元素](https://blog.csdn.net/qq413886183/article/details/116146169)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [删除数组指定元素——C++实现](https://blog.csdn.net/ling08140814/article/details/106398785)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值