簡體   English   中英

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

[英]How to initialize a list of std::vector's values in 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

我需要用值來初始化globalArr:“a”,“b”,“c”,“e”,“f”,“g”(在一個維度上)。 我不需要二維數組。 我做錯了什么?

我可以這樣做:

globalArr.push_back( arr1 ); // with the for loop inserting each value of arr1
globalArr.push_back( arr2 );

但是這里的globalArr不再是const :)我需要所有三個向量的相同類型。

你可以實現一個只對它們求和的函數。 說, 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;
}

然后使用它:

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;

該函數可以命名為任何東西,我只是為了簡單而選擇+

在即將推出的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, ","));
}

實例

如果你要做的只是簡單地將arr1arr2元素放入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的向量。 將for循環放在函數中並調用該函數兩次。 多一點工作,但可能更清晰的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM