Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a list of std::vector's values in C++11?

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.

like image 455
JavaRunner Avatar asked Feb 08 '23 07:02

JavaRunner


1 Answers

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.

like image 172
Barry Avatar answered Feb 16 '23 02:02

Barry