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

Kris Dunning
  • 127
  • 2
  • 9

2 Answers2

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188
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);
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 2
    In C++11 we have proper initialisers, no need for the first of your methods. – Konrad Rudolph Jan 26 '12 at 14:19
  • @KonradRudolph: good point (although the question does specifically ask about initialising from an array, so I'll leave that method in the answer). – Mike Seymour Jan 26 '12 at 14:26
  • 2
    Long before C++11, we had `begin` and `end` in our personal tool kit. And they're mostly relevant to pre-C++11. – James Kanze Jan 26 '12 at 14:52
  • 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! – Kris Dunning Jan 27 '12 at 10:14