5

I wish to initialise a vector using an array of std::strings.

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".

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I wasn't certain whether I'd completely missed any other potential methods of initialising things.
3

In C++11, we have std::begin and std::end, which work for both STL-style containers and built-in arrays:

#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:

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

4 Comments

In C++11 we have proper initialisers, no need for the first of your methods.
@KonradRudolph: good point (although the question does specifically ask about initialising from an array, so I'll leave that method in the answer).
Long before C++11, we had begin and end in our personal tool kit. And they're mostly relevant to pre-C++11.
Thanks for this. It doesn't quite fit into the code I'm currently working on, but it is good to know. I should also have stated that I am not using C++11, but again, thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.