Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best initialize a vector of strings in C++?

Tags:

c++

I generally love python's syntax.

v = ["sds", "bsdf", "dsdfaf"]

What I currently have in C++ looks like this

vector<string> v;
v.push_back("sds");
v.push_back("bsdf");
v.push_back("dsdfaf");

Is there a better/cleaner way to do this? Note that v remains unchanged after initialization. So an array might work too but the problem with array is that I need to also hardcode the length of the array in my code.

char* v[] = {"sds", "bsdf", "dsdfaf"};
for (int i = 0; i < 3; ++i) do_something(v[i]);

EDIT: I don't have C++11. My Compiler is gcc 4.1.2

like image 500
Mohammad Moghimi Avatar asked Jan 16 '14 21:01

Mohammad Moghimi


1 Answers

C++03 solutions:

Use vector constructor that takes a pair of iterators.

char* arr[] = {"sds", "bsdf", "dsdfaf"};
vector<string> v(arr, arr + sizeof(arr)/sizeof(arr[0]));

Use an array if the length doesn't need to change after initialization. To avoid hardcoding array length use this function template to deduce size

template<typename T, std::size_t N>
std::size_t length_of( T const (&)[N] ) { return N; }

char* v[] = {"sds", "bsdf", "dsdfaf"};
for (int i = 0; i < length_of(v); ++i) do_something(v[i]);

Note that this won't work within a function to which you pass a char **.


Use boost::assign::list_of

using boost::assign::list_of;
std::vector<std::string> v = list_of("sds")("bsdf")("dsdfaf");
like image 148
Praetorian Avatar answered Sep 27 '22 17:09

Praetorian