【C++】vector迭代器iterator及删除元素

vector迭代器iterator

        vector<>::iterator是访问元素地址的迭代器,使用其可以循环访问元素,使用*可以获取访问元素的值。当然也可以用下标访问。

vector<Object>::iterator it;
for (it = objects.begin(); it != objects.end();){
    cout<<*it;
}

std::vector::erase()

  函数原型:iterator erase (iterator position);  //删除指定元素

       iterator erase (iterator first, iterator last);  //删除指定范围内的元素

  返回值:指向删除元素(或范围)的下一个元素。(An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.)

示例代码:

        循环vector,根据条件删除元素,注意vector为空的时候需要break跳出循环。循环时如果删除了元素,则自动指向下一个元素,否则需要手动指向下一个元素。

struct Object
{
	cv::Rect_<float> rect;
	int label;
	float prob;
	std::string objStr;
};

void area_filter(std::vector<Object>& objects, int& img_h, int& img_w, float& scale) {

	float box_area = 0.;
	float image_area = img_h * img_w * 1.0;
	vector<Object>::iterator it;
	for (it = objects.begin(); it != objects.end();)
	{
		box_area = (*it).rect.width * (*it).rect.height;
		if (box_area / image_area > this->area_thr)
			objects.erase(it);
		else
			++it;
	}
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值