Add element to function in place C++ Python code:
l1 = [1, 2, 3]
l2 = l1 + [4]
print(l2) #[1, 2, 3, 4]
l3 = l1+l2
print(l3) #[1, 2, 3, 1, 2, 3, 4]
Is there a way to do this in C++
Add element to function in place C++ Python code:
l1 = [1, 2, 3]
l2 = l1 + [4]
print(l2) #[1, 2, 3, 4]
l3 = l1+l2
print(l3) #[1, 2, 3, 1, 2, 3, 4]
Is there a way to do this in C++
You clarified in a comment that you want to do it "in place". In C++17 there isn't an operator or function in the standard library for concatenating two vectors (or containers), but it is pretty easy to create one yourself:
template <class T>
std::vector<T> concat(const std::vector<T>& v1, const std::vector<T>& v2)
{
auto res = v1;
res.insert(res.end(), v2.begin(), v2.end());
return res;
}
In C++20 all this changes as we will get ranges.
Until then you can use the ranges-v3 library (on which the standard ranges are based):
views::concat(v1, v2);
This returns a range. That should be enough as you should take range views as parameters or at least iterators. The advantage is that views are lazy. They don't do the actual transformations until you iterate over them and don't create new containers. If you however still need a vector you can do that like this:
#include <range/v3/view.hpp>
using namespace ranges;
auto test()
{
std::vector v1{10, 20, 30};
std::vector v2{1, 2, 3, 4, 5};
auto v = views::concat(v1, v2) | to<std::vector>();
}
There has been a comment about creating an overloaded operator+ instead of the function. That would be a bad idea for a few reasons:
Overloading an operator with only standard classes as parameters is a bad idea as you can't open namespace std to define it there and defining it elsewhere will cause problems with ADL.
Second, even if you could, a golden rule is to overload an operator to do expected things. In this case, an operator+ would be expected by (some/most) people to do element-wise addition.
I believe you're trying to add an element to a vector in c++.
vector<int> v; // { }
v.push_back(10); // { 10 }
To append one vector to another vector, you could use insert
vector<int> v = { 11, 12 };
vector<int> v2 = { 13, 14 };
v.insert(v.end(), v2.begin(), v2.end()); // { 11, 12, 13, 14 }
The first parameter to insert is an iterator pointing to where you want the second vector's elements to be inserted. The 2nd and 3rd parameters are the iterators pointing to the beginning and end of the second vector, they denote the boundaries of which elements to insert into the first vector.
This operation effectively appends the second vector into the first vector.