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.
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;
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With