简体   繁体   English

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

[英]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). 我需要用值来初始化globalArr:“a”,“b”,“c”,“e”,“f”,“g”(在一个维度上)。 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. 但是这里的globalArr不再是const :)我需要所有三个向量的相同类型。

You could implement a function that just sums them. 你可以实现一个只对它们求和的函数。 Say, operator+ : 说, 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. 该函数可以命名为任何东西,我只是为了简单而选择+

In the upcoming Ranges TS , it will be possible to write the solution by @Barry as 在即将推出的Ranges 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 Example 实例

If all you're trying to do is simply put the elements of arr1 and arr2 into globaArr , why not use a for loop? 如果你要做的只是简单地将arr1arr2元素放入globaArr ,为什么不使用for循环呢?

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. 更好的是,只需编写一个函数,它接受globaArr和你想要添加到globaArr的向量。 Put the for loop in the function and call the function twice. 将for循环放在函数中并调用该函数两次。 A little more work, but probably cleaner code. 多一点工作,但可能更清晰的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM