I have a std::vector<char>
v
that is created at runtime, and I would like to append {'a', 'k', 'e', 'e', 'f'}
to it.
I could just do v.emplace_back
on each individual letter, or I can create an l-value vector and store {'a', 'k', 'e', 'e', 'f'}
and then use insert
with iterators, but I don't like either of these approaches because the former requires additional lines (I have to do this in several parts of the code), and the letter requires creating an l-value vector (might be some efficiency issues)?
Is there a better way to do this? I'm essentially looking for a 1-2 liner, e.g., something like
v.emplace_back({'a', 'k', 'e', 'e', 'f'}); // doesn't work
I forgot to mention that v
's capacity is reserved to accommodate this temporary vector -- this is probably not relevant, however?
CodePudding user response:
vector::insert()
has an overload that accepts a std::initializer_list
as input, which can be constructed from a brace-list, eg:
v.insert(v.end(), {'a', 'k', 'e', 'e', 'f'});
CodePudding user response:
Here is one (gross, error prone) way to do it:
std::vector<char> vect;
auto const & x = "abcdef";
vect.insert(vect.end(), &(x[0]), x sizeof(x) - 1)
No temporary objects, x
is just a string literal.
Personally, I definitely would write your code as readable as possible (i.e. not like my snippet above). Don't care about any (imagined) efficiency loss unless you measured it and figured out what the problematic piece of code is.