从循环内的向量中删除项目

时间:2014-10-21 14:57:19

标签: c++ opencv vector

我想从循环内的向量中删除一些索引 我目前有以下代码:

static void store_faces(Mat image, vector<Rect> faces,  string path, string fileName){

 SkinDetector mySkinDetector;
 int counter = 0;
 for(int i = 0; i < faces.size(); i++){
    Mat temp = image(faces.at(i));

    double ratio= mySkinDetector.getSkin(temp);
    cout << "found face skin ratio.. " << ratio << endl;

    string file_name = path+ fileName + "_"+ NumberToString(counter)+".jpg";
    imwrite(file_name, temp);
    counter+=1;
  }
}

我要删除那些ratio < 0.5的面孔。如何从vector<Rect> faces

中删除项目

3 个答案:

答案 0 :(得分:5)

正确的方法是:

std::vector<Rect> vec = ...;
auto tail = std::remove_if(vec.begin(), vec.end(), [&](Rect const & rect) -> bool {
    return mySkinDetector.getSkin(image(rect)) < 0.5;
});

vec.erase(tail, vec.end());

答案 1 :(得分:2)

你可以这样做:

void fct(vector<Rect> faces)
{
    for(vector<Rect>::iterator it=faces.begin(); it!=faces.end(); /*nothing here*/)
    {
        if( condition )
            it = faces.erase(it)
        else
            ++it;
}

答案 2 :(得分:-1)

应该是:

for(int i = 0; i < faces.size(); i++){
    Mat temp = image(faces.at(i));

    //[...]

    if(ratio<0.5)
       faces.erase(faces.begin()+i);

    //[...]
}