简体   繁体   English

std :: vector :: erase vs“swap and pop”

[英]std::vector::erase vs “swap and pop”

The "normal" way of deleting an element from a vector goes like this: 从向量中删除元素的“正常”方式如下:

vec.erase(vec.begin() + index);

But in theory it's faster just to do this: 但从理论上说,这样做更快:

if (vec.size() > 1)
{
    std::iter_swap(vec.begin() + index, vec.end() - 1);
    vec.pop_back();
}
else
{
    vec.clear();
}

Is there any reason to not use the latter? 有没有理由不使用后者?

The second case does not preserve the order of the elements in the vector. 第二种情况不保留向量中元素的顺序。 If this is a sorted vector or the order is important then you have just broken that in the second case where the first case would leave the order intact. 如果这是一个有序的向量或者顺序很重要那么你刚刚在第二种情况下破坏了第一种情况会使订单保持原样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM