Concatenating two std::vectors

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

How do I concatenate two std::vectors?

25条回答
  •  日久生厌
    2020-11-22 12:26

    If what you're looking for is a way to append a vector to another after creation, vector::insert is your best bet, as has been answered several times, for example:

    vector first = {13};
    const vector second = {42};
    
    first.insert(first.end(), second.cbegin(), second.cend());
    

    Sadly there's no way to construct a const vector, as above you must construct and then insert.


    If what you're actually looking for is a container to hold the concatenation of these two vectors, there may be something better available to you, if:

    1. Your vector contains primitives
    2. Your contained primitives are of size 32-bit or smaller
    3. You want a const container

    If the above are all true, I'd suggest using the basic_string who's char_type matches the size of the primitive contained in your vector. You should include a static_assert in your code to validate these sizes stay consistent:

    static_assert(sizeof(char32_t) == sizeof(int));
    

    With this holding true you can just do:

    const u32string concatenation = u32string(first.cbegin(), first.cend()) + u32string(second.cbegin(), second.cend());
    

    For more information on the differences between string and vector you can look here: https://stackoverflow.com/a/35558008/2642059

    For a live example of this code you can look here: http://ideone.com/7Iww3I

提交回复
热议问题