I have a problem with the following code:
const std::vector < std::string > arr1 = { "a", "b", "c" };
const std::vector < std::string > arr2 = { "e", "f", "g" };
const std::vector < std::string > globaArr = { arr1, arr2 }; // error
I need to initialize globalArr with values: "a", "b", "c", "e", "f", "g" (in one dimension). I don't need to have two-dimensional array. What do I do wrong?
I can do something like this:
globalArr.push_back( arr1 ); // with the for loop inserting each value of arr1
globalArr.push_back( arr2 );
but here the globalArr is not const anymore :) I need the same type for all three vectors.
You could implement a function that just sums them. Say, operator+
:
template <class T>
std::vector<T> operator+(std::vector<T> const& lhs,
std::vector<T> const& rhs)
{
auto tmp(lhs);
tmp.insert(tmp.end(), rhs.begin(), rhs.end());
return tmp;
}
And then just use that:
const std::vector<std::string> arr1 = { "a", "b", "c" };
const std::vector<std::string> arr2 = { "e", "f", "g" };
const std::vector<std::string> sum = arr1 + arr2;
The function could be named anything, I just picked +
for simplicity.
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