How stupid is initializing a vector from the concatenation of 2 other vectors?

Recently, I wanted to construct quickly a constant vector being the result of the concatenation of two other vectors using a one liner code, and if possible, without rewriting the concatenation by myself. I am a very very very lazy programmer.

Each vector is the result of two existing functions. Let’s call them f() and g():

It certainly exists an obvious solution for this kind of issue. Either by the std::vector library itself or somewhere in the community like boost. Sure of it ? Not really.

I started googling to find a generic solution and found several proposals on stackoverflow. But none of them gave me satisfaction. No one comes with a one-liner solution.

The closest possible solutions I found were on boost: boost::range::push_back

This does not compile, because an rvalue cannot be passed to a non-const reference.

Another option is boost::range::join algorithm:

This does not compile, because class std::vector does not provide a constructor with another container/range type. You could argue that it provides a c-tor with generic input iterator. But I do not have any clue how to pass begin() and end() of the same temporary at once in the same line.

The final trick was given by Jeffrey Flinn on the boost user mailing list: use of copy_range on the result of join.

 

This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *