简体   繁体   English

使用数组初始化std :: string的向量

[英]Initialising a vector of std::string with an array

I wish to initialise a vector using an array of std::string s. 我希望使用std::string s数组初始化一个向量。

I have the following solution, but wondered if there's a more elegant way of doing this? 我有以下解决方案,但想知道是否有更优雅的方式这样做?

std::string str[] = { "one", "two", "three", "four" };
vector< std::string > vec;
vec = vector< std::string >( str, str + ( sizeof ( str ) /  sizeof ( std::string ) ) );

I could, of course, make this more readable by defining the size as follows: 当然,我可以通过定义大小来使其更具可读性,如下所示:

int size =  ( sizeof ( str ) /  sizeof ( std::string ) );

and replacing the vector initialisation with: 并用以下代码替换向量初始化:

vec = vector< std::string >( str, str + size );

But this still feels a little "inelegant". 但这仍然感觉有点“不优雅”。

Well the intermediate step isn't needed: 那么不需要中间步骤:

std::string str[] = { "one", "two", "three", "four" };
vector< std::string > vec( str, str + ( sizeof ( str ) /  sizeof ( std::string ) ) );

In C++11 you'd be able to put the brace initialization in the constructor using the initializer list constructor. 在C ++ 11中,您可以使用初始化列表构造函数将大括号初始化放在构造函数中。

In C++11, we have std::begin and std::end , which work for both STL-style containers and built-in arrays: 在C ++ 11中,我们有std::beginstd::end ,它们适用于STL样式容器和内置数组:

#include <iterator>

std::vector<std::string> vec(std::begin(str), std::end(str));

although, as mentioned in the comments, you usually won't need the intermediate array at all: 虽然,如评论中所述,您通常根本不需要中间数组:

std::vector<std::string> vec {"one", "two", "three", "four"};

In C++03, you could use a template to deduce the size of the array, either to implement your own begin and end , or to initialise the array directly: 在C ++ 03中,您可以使用模板来推断数组的大小,以实现自己的beginend ,或者直接初始化数组:

template <typename T, size_t N>
std::vector<T> make_vector(T &(array)[N]) {
    return std::vector<T>(array, array+N);
}

std::vector<std::string> vec = make_vector(str);

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

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