Reputation: 4686
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
Upvotes: 8
Views: 15380
Reputation: 3481
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.
That's not true. You can get the array size the canonical way one does so like the following:
#include <iostream>
int main()
{
char const * const v[] = {"sds", "bsdf", "dsdfaf"};
// Only works when array length is known at compile-time.
size_t const len = sizeof(v) /sizeof(v[0]);
for (size_t i = 0; i < len; ++i)
std::cout << v[i] << '\n';
}
The output is:
$ g++ -Wall foo.cpp ; ./a.out
sds
bsdf
dsdfaf
Upvotes: 0
Reputation: 109119
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 **
.
using boost::assign::list_of;
std::vector<std::string> v = list_of("sds")("bsdf")("dsdfaf");
Upvotes: 4
Reputation: 76240
Is there a better/cleaner way to do this?
You can use the brace initialization syntax:
std::vector<std::string> v { "sds", "bsdf", "dsdfaf" };
Note that v remains unchanged after initialization.
You can use an std::array
(since C++11):
std::array<std::string, 3> a {{ "sds", "bsdf", "dsdfaf" }};
You'll still have to "hardcode" the number of elements, but it's not dynamic anyway, so you don't lose much.
Upvotes: 2
Reputation: 500367
In C++11 you can write:
std::vector<std::string> v{"sds", "bsdf", "dsdfaf"};
Upvotes: 4