Concatenating two std::vectors

后端 未结 25 2616
予麋鹿
予麋鹿 2020-11-22 12:00

How do I concatenate two std::vectors?

25条回答
  •  不要未来只要你来
    2020-11-22 12:32

    If you are interested in strong exception guarantee (when copy constructor can throw an exception):

    template
    inline void append_copy(std::vector& v1, const std::vector& v2)
    {
        const auto orig_v1_size = v1.size();
        v1.reserve(orig_v1_size + v2.size());
        try
        {
            v1.insert(v1.end(), v2.begin(), v2.end());
        }
        catch(...)
        {
            v1.erase(v1.begin() + orig_v1_size, v1.end());
            throw;
        }
    }
    

    Similar append_move with strong guarantee can't be implemented in general if vector element's move constructor can throw (which is unlikely but still).

提交回复
热议问题