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

vector迭代器iterator

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

vector::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_ rect;
	int label;
	float prob;
	std::string objStr;
};

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

	float box_area = 0.;
	float image_area = img_h * img_w * 1.0;
	vector::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;
	}
} 
  

你可能感兴趣的:(c/c++,c++,java,数据结构)