2013-09-30 12 views
3

首先,如果這是一個致盲的簡單而明顯的問題,我想表示歉意。我知道這對擁有技術訣竅的人來說是相當容易的。 C++ 11允許向量以列表形式初始化向量:在Pre C++中將字符串列表填充到矢量中11

std::vector<std::string> v = { 
    "this is a", 
    "list of strings", 
    "which are going", 
    "to be stored", 
    "in a vector"}; 

但是這在舊版本中不可用。我一直認爲最好的方式來填充一個字符串矢量,到目前爲止我真的可以拿出的唯一事情是:

std::string s1("this is a"); 
std::string s2("list of strings"); 
std::string s3("which are going"); 
std::string s4("to be stored"); 
std::string s5("in a vector"); 

std::vector<std::string> v; 
v.push_back(s1); 
v.push_back(s2); 
v.push_back(s3); 
v.push_back(s4); 
v.push_back(s5); 

它的工作原理,但它是一個有點煩瑣寫我相信有更好的方法。

+3

使用的數組:

char const* array[] = { "this is a", "list of strings", "which are going", "to be stored", "in a vector" }; std::vector<std::string> vec(begin(array), end(array)); 

功能begin()end()這樣被定義初始化它。你應該能夠找到關於'std :: vector'教程的例子。 – chris

+0

看看這個相關的問題:http://stackoverflow.com/questions/231491/how-to-initialize-const-stdvectort-like-ac-array/231495#231495 – Ferruccio

回答

6

的規範的方式是在合適的報頭,以限定begin()end()功能和使用是這樣的:

template <typename T, int Size> 
T* begin(T (&array)[Size]) { 
    return array; 
} 
template <typename T, int Size> 
T* end(T (&array)[Size]) { 
    return array + Size; 
} 
+1

+1對於'begin()'和'end ()'函數。 –

+1

@NemanjaBoric:當然,我正在使用'begin()'和'end()'!據我所知,我是第一個在[上個千年]的某個時候公開描述這項技術的人(https://groups.google.com/forum/#!topic/comp.lang.c++.moderated/0Pr5ecSTwZw) 。這些功能模板也是第一個[Boost貢獻](http://hepunx.rl.ac.uk/BFROOT/dist/packages/boost/V01-27-00-04/libs/array_traits/array_traits.html)。 –

+0

只是爲了像我這樣的人,不知道這一點的好處,這個功能現在似乎在[Boost.Range庫]中(http://www.boost.org/doc/libs/1_54_0/libs /range/doc/html/index.html)。 –

1

如果你被預C++ 11 C++「困住」,只有幾種選擇,它們不一定是「更好」。

首先,您可以創建一個常量C字符串數組並將它們複製到矢量中。你可以節省一些輸入,但是你有一個複製循環。

二,如果你可以使用提升,你可以use boost::assign's list_of as described in this answer

4

克里斯指出,你可以所有文字存入數組,然後從該數組初始化向量:

#include <vector> 
#include <iostream> 
#include <string> 

int main() 
{ 
     const char* data[] = {"Item1", "Item2", "Item3"}; 
     std::vector<std::string> vec(data, data + sizeof(data)/sizeof(const char*)); 
} 

你並不需要顯式轉換到std::string