Get random element and remove it

前端 未结 3 2235
眼角桃花
眼角桃花 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:08

    You have the solution, and it seems perfectly fine. The idiomatic way to write it in C++ is not to create another class (and please don't inherit from std::vector), but just to write a function:

    template 
    void remove_at(std::vector& v, typename std::vector::size_type n)
    {
        std::swap(v[n], v.back());
        v.pop_back();
    }
    

    Usage:

    remove_at(v, 42);
    

    This offers the same exception guarantee as std::swap.

    Now if you want to return the object, and you have access to a C++11 compiler, you can do it the following way. The difficult part is to provide the basic exception guarantee in all cases:

    template 
    T remove_at(std::vector&v, typename std::vector::size_type n)
    {
        T ans = std::move_if_noexcept(v[n]);
        v[n] = std::move_if_noexcept(v.back());
        v.pop_back();
        return ans;
    }
    

    Indeed, you don't want the vector to be left in an invalid state if an exception is thrown during a move operation.

提交回复
热议问题