JavaRunner
JavaRunner

Reputation: 2545

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.

Upvotes: 4

Views: 223

Answers (3)

TemplateRex
TemplateRex

Reputation: 70516

In the upcoming Ranges TS, it will be possible to write the solution by @Barry as

#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 Example

Upvotes: 2

Barry
Barry

Reputation: 302718

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.

Upvotes: 6

Chad Lewis
Chad Lewis

Reputation: 141

If all you're trying to do is simply put the elements of arr1 and arr2 into globaArr, why not use a for loop?

Example:

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));
}

Better yet, just write a function that takes in globaArr and a vector that you want to add to globaArr from. Put the for loop in the function and call the function twice. A little more work, but probably cleaner code.

Upvotes: 0

Related Questions