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