How do I concatenate two std::vector
s?
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 vector
s, there may be something better available to you, if:
vector
contains primitivesconst
containerIf 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