How to initialize a list of std :: vector 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 the values: "a", "b", "c", "e", "f", "g" (in one dimension). I do not need to have a two-dimensional array. What am I doing 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 globalArr is no longer const :) I need the same type for all three vectors.

+4
source share
3 answers

You can implement a function that simply sums them up. Let's 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 this:

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 can be called anything, I just chose +for simplicity.

+6

TS @Barry

#include <range/v3/all.hpp>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

int main()
{
    using namespace ranges;

    const std::vector<std::string> arr1 = { "a", "b", "c" };
    const std::vector<std::string> arr2 = { "e", "f", "g" };
    const auto sum = view::concat(arr1, arr2) | to_vector;

    std::copy(sum.begin(), sum.end(), std::ostream_iterator<std::string>(std::cout, ","));
}

Live

+2

, , arr1 arr2 globaArr, for?

:

for ( int i = 0; i < (int)arr1.size(); i++ ) {
    globaArr.push_back(arr1.at(i));
}

for ( int i = 0; i < (int)arr2.size(); i++ ) {
    globaArr.push_back(arr1.at(i));
}

, , globaArr , globaArr from. for . , , , .

0

All Articles