[英]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, ","));
}
如果你要做的只是簡單地將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
的向量。 將for循環放在函數中並調用該函數兩次。 多一點工作,但可能更清晰的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.