I had trouble searching for potential duplicates because I’m not sure what the correct terminology is.
If I have many vectors which are already created, how can I loop through them? To make things simple, suppose I have three vectors of strings named "vec_one", "vec_two", "vec_three".
I want to do something like:
for i in ("vec_one", "vec_two", "vec_three") {
for (vector<string>::const_iterator iter = i.begin(); iter != i.end(); ++iter) {
//do something with the elements ***and I need to access "i"***, that is, the vector name.
}
}
This would be the same as writing three different for loops, but would be more readable and in fact I have more than three in my non-simple application.
Note that because I need to access the vector name (see the comment), I can’t just merge them all together and then run one loop.
You could put the the vectors in a
vector<std::pair<std::string, std::vector<...>*>:That way you can get the name easily from the outer iterator.
If you use C++11 you can use
std::arrayinstead:In C++03 you could use buildin arrays instead, but unless the extra overhead for the
vectoris a problem for you (unlikely) I don’t see a compelling reason to do so.boost::arrayis also a noteworthy alternative if you can’t use C++11If you do need the absolute optimal performance it might be worthwile to directly use
const char*instead ofstd::stringfor the names.