如何在C++ 11中初始化std :: vector的值列表?

Jav*_*ner 4 c++ vector stdvector c++11

我有以下代码的问题:

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
Run Code Online (Sandbox Code Playgroud)

我需要用值来初始化globalArr:"a","b","c","e","f","g"(在一个维度上).我不需要二维数组.我做错了什么?

我可以这样做:

globalArr.push_back( arr1 ); // with the for loop inserting each value of arr1
globalArr.push_back( arr2 );
Run Code Online (Sandbox Code Playgroud)

但是这里的globalArr不再是const :)我需要所有三个向量的相同类型.

Bar*_*rry 6

你可以实现一个只对它们求和的函数.说,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;
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

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;
Run Code Online (Sandbox Code Playgroud)

该功能可以命名为任何东西,我只是+为了简单而选择.