Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construction a vector from the concatenation of 2 vectors

Is there a way to construct a vector as the concatenation of 2 vectors (Other than creating a helper function?)

For example:

const vector<int> first = {13};
const vector<int> second = {42};
const vector<int> concatenation = first + second;

I know that vector doesn't have an addition operator like string, but that's the behavior that I want. Such that concatenation would contain: 13 and 42.

I know that I can initialize concatenation like this, but it prevents me from making concatenation const:

vector<int> concatenation = first;
first.insert(concatenation.end(), second.cbegin(), second.cend()); 
like image 264
Jonathan Mee Avatar asked Feb 18 '16 15:02

Jonathan Mee


People also ask

How to concatenate two vectors in C++?

Concatenate two vectors in C++. In this post, we will discuss how to join or concatenate two vectors in C++. The resulting vector will contain all of the element of first vector followed by all elements of the second vector in same order. For example, consider below vectors x and y which concatenates to vector v. Input: x = { 1, 2, 3 };

How can I combine two vectors into one?

The trick is to create a vector proxy: a wrapper class which manipulates references to both vectors, externally seen as a single, contiguous one. std::vector<int> A { 1, 2, 3, 4, 5}; std::vector<int> B { 10, 20, 30 }; VecProxy<int> AB (A, B); // ----> O (1).

How can I speed up concatenation of vectors?

Look here: stackoverflow.com/a/64102335/7110367 Demo. I predict this will be the appropriate answer in 2023 or so. A general performance boost for concatenate is to check the size of the vectors. And merge/insert the smaller one with the larger one.

How do you concatenate matrices in MATLAB?

Concatenating Matrices. You can also use square brackets to join existing matrices together. This way of creating a matrix is called concatenation. For example, concatenate two row vectors to make an even longer row vector.


2 Answers

No, it's not possible if you require that

  • no helper function is defined, and
  • the resulting vector can be declared const.
like image 181
Frerich Raabe Avatar answered Nov 07 '22 12:11

Frerich Raabe


template<typename T>
std::vector<T> operator+(const std::vector<T>& v1, const std::vector<T>& v2){
    std::vector<T> vr(std::begin(v1), std::end(v1));
    vr.insert(std::end(vr), std::begin(v2), std::end(v2));
    return vr;
}

This does require a helper "function", but at least it allows you to use it as

const vector<int> concatenation = first + second;
like image 21
Matt Jordan Avatar answered Nov 07 '22 11:11

Matt Jordan