Is there a way to construct a vector
as the concatenation of 2 vector
s (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());
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 };
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).
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.
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.
No, it's not possible if you require that
const
.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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With