Question

Firstly, I'd like to apologise if this is a blinding simple and obvious question. I know it's a fairly easy one to people with the know-how. C++11 allows vectors to be initialised in list form:

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

But this isn't available in older versions. I've been trying to think of the best way to populate a vector of strings and so far the only thing I can really come up with is:

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

It works, but it's a bit of a chore to write and I'm convinced there's a better way.

Was it helpful?

Solution

The canonical way is to define begin() and end() functions in a suitable header and use something like this:

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

The functions begin() and end() are defined like this:

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

OTHER TIPS

As chris noted, you could store all literals into the array, and then initialize vector from that array:

#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*));
}

You don't need explicit conversion to std::string.

If you're "stuck" with pre-C++11 C++, there are only a couple of alternatives and they're not necessarily "better".

First, you can create an array of constant C strings and copy them into the vector. You might save a little typing, but then you have a copy loop in there.

Second, if you can use boost, you could use boost::assign's list_of as described in this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top