Merge vector and initializer_list into initialization of vector <vector <T>>?
Let's say that I initialize a vector<vector<string>> as follows:
vector<vector<string>> v; v = {{ {"a", "b", "c"}, {"aa", "bb"}, {"xyz", "yzx", "zxy"}, {} }}; Now suppose I want to add an existing vector<string> to some elements of v . For instance:
vector<string> suffix {{"1", "2", "3"}}; vector<vector<string>> v; v = {{ {"a", "b", "c"} + suffix, {"aa", "bb"}, {"xyz", "yzx", "zxy"} + suffix, {} }}; This syntax clearly does not work, because operator+ not defined this way.
I understand that it is possible to build v first way and then write
vector<int> indices = {0, 2}; for(int i: indices) v[i].insert(v[i].end(), suffix.begin(), suffix.end()); But this is not convenient, because I can have several suffix vectors that are bound to arbitrary v[i] . I want suffix be along with v[i] initialization, so it makes sense, and I don't need to change indexes if I add / remove elements from v initialization.
One possible solution is to use a helper function that adds.
vector<string> appendStrings(vector<string>&& s1, vector<string> const& s2) { s1.insert(s1.end(), s2.begin(), s2.end()); return s1; } And use it to initialize the variable.
vector<string> suffix {{"1", "2", "3"}}; vector<vector<string>> v = {{ appendStrings({"a", "b", "c"}, suffix), {"aa", "bb"}, appendStrings({"xyz", "yzx", "zxy"}, suffix), {} }}; Update
More efficient implementation of appendStrings (thanks to @Yakk):
vector<string> appendStrings(initializer_list<char const*>&& s1, vector<string> const& s2) { vector<string> ret. ret.reserve(s1.size() + s2.size()); for (auto item : s1 ) { ret.emplace_back(item); } ret.insert(ret.end(), s2.begin(), s2.end() ); return ret; }