Initializing a std :: string vector using an array

I want to initialize a vector using the std::strings array .

I have the following solution, but wondered if there is a more elegant way to do 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 specifying the size as follows:

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

and replacing vector initialization with:

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

But it still seems a little "inelegant."

+5
source share
2 answers

Well, an intermediate step is not needed:

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

In C ++ 11, you can put parenthesis initialization in a constructor using the initializer list constructor.

+4
source

In C ++ 11, we have std::beginand std::endthat work for both STL-style containers and inline arrays:

#include <iterator>

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

, , :

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

++ 03 , begin, end, :

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);
+3

All Articles