Most efficient way of erasing/deleting multiple std::vector elements while retaining original order?

前端 未结 7 1437
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 17:37


i have a std::vector and a second container holding iterators or indexes (no keys, i want constant access to the element) to this vector for del

7条回答
  •  再見小時候
    2020-12-23 18:27

    In there is a remove_if function which squeezes all values not removed to the front maintaining the order. This works if those 200 elements can be purely determined by the values, not index.

    This is essentially the Erase-remove idiom you have linked to. remove_if is guaranteed to perform O(N) comparisons (and at most O(N) copyings), which would be more efficient than sorting (O(N log N)), although your last option doesn't actually require sorting if the indices are determined from values (just scan in the reversed direction while copying).

    Nevertheless, using remove_if (if you can) is better than the other 2 options because the implementation has already been written for you, so there's less chance of logical error and conveys better what (not how) to do.

提交回复
热议问题