Get random element and remove it

前端 未结 3 2234
眼角桃花
眼角桃花 2021-02-14 15:30

Problem: I need to get a random element for a container and also delete it from that container. Container does not need to be sorted. I dont care about the order.

3条回答
  •  再見小時候
    2021-02-14 16:04

    With O(n) complexity

    vec.erase(vec.begin() + randomIdx); randomIdx would be between 0 and vec.size()-1

    If you want O(1) complexity you could either use the list container for example or swap the element with the last one and delete this instead. ( As mentioned by the others )

提交回复
热议问题