使用索引擦除 std::vector 中的元素 [英] Erasing elements in std::vector by using indexes

查看:35
本文介绍了使用索引擦除 std::vector 中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std::vector 并且我需要删除给定索引处的所有元素(向量通常具有高维数).我想知道,考虑到应保留原始向量的顺序,哪种方法是执行此类操作的最有效方法.

I've a std::vector<int> and I need to remove all elements at given indexes (the vector usually has high dimensionality). I would like to know, which is the most efficient way to do such an operation having in mind that the order of the original vector should be preserved.

虽然,我找到了关于这个问题的相关帖子,其中一些需要删除一个 单个元素多个元素,其中remove-erase idiom 似乎是一个很好的解决方案.但是,就我而言,我需要删除多个元素,并且由于我使用的是索引而不是直接值,因此无法应用 remove-erase idiom,对吗?下面给出了我的代码,我想知道在效率方面是否可以做得更好?

Although, I found related posts on this issue, some of them needed to remove one single element or multiple elements where the remove-erase idiom seemed to be a good solution. In my case, however, I need to delete multiple elements and since I'm using indexes instead of direct values, the remove-erase idiom can't be applied, right? My code is given below and I would like to know if it's possible to do better than that in terms of efficiency?

bool find_element(const vector<int> & vMyVect, int nElem){
    return (std::find(vMyVect.begin(), vMyVect.end(), nElem)!=vMyVect.end()) ? true : false;
}

void remove_elements(){

    srand ( time(NULL) );

    int nSize = 20;
    std::vector<int> vMyValues;
    for(int i = 0; i < nSize; ++i){
            vMyValues.push_back(i);
    }

    int nRandIdx;
    std::vector<int> vMyIndexes;
    for(int i = 0; i < 6; ++i){
        nRandIdx = rand() % nSize;
        vMyIndexes.push_back(nRandIdx);
    }

    std::vector<int> vMyResult;
    for(int i=0; i < (int)vMyValues.size(); i++){
        if(!find_element(vMyIndexes,i)){
            vMyResult.push_back(vMyValues[i]);
        }
    }
}

推荐答案

我认为如果您只是对索引进行排序,然后从向量中从最高到最低删除这些元素,那么效率会更高.删除列表上的最高索引不会使您要删除的较低索引无效,因为只有高于已删除元素的元素才会更改其索引.

I think it could be more efficient, if you just just sort your indices and then delete those elements from your vector from the highest to the lowest. Deleting the highest index on a list will not invalidate the lower indices you want to delete, because only the elements higher than the deleted ones change their index.

是否真的更有效将取决于排序的速度.关于此解决方案的另一个优点是,您不需要值向量的副本,您可以直接处理原始向量.代码应如下所示:

If it is really more efficient will depend on how fast the sorting is. One more pro about this solultion is, that you don't need a copy of your value vector, you can work directly on the original vector. code should look something like this:

... fill up the vectors ...

sort (vMyIndexes.begin(), vMyIndexes.end());

for(int i=vMyIndexes.size() - 1; i >= 0; i--){
    vMyValues.erase(vMyValues.begin() + vMyIndexes[i])
}

这篇关于使用索引擦除 std::vector 中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆