I would like to do a stuff like this in c++ :
for (int i = 0, i < 3; ++i)
{
const auto& author = {"pierre", "paul", "jean"}[i];
const auto& age = {12, 45, 43}[i];
const auto& object = {o1, o2, o3}[i];
print({"even", "without", "identifier"}[i]);
...
}
Does everyone know how to do this kind of trick ? I do it a lot in python. It helps me to factorize code nicely.
Looks like you should have used a vector of your custom class with author
, age
, object
and whatever
attributes, put it in a vector and do range for-loop over it - that would be idiomatic in C++:
struct foo
{
std::string author;
int age;
object_t object;
whatever_t whatever;
};
std::vector<foo> foos = { /* contents */ };
for(auto const& foo : foos)
{
// do stuff
}
If you really want to, you can do:
const auto author = std::vector<std::string>{"pierre", "paul", "jean"}[i];
// ^ not a reference
but I'm not sure how well this will be optimised. You could also declare those vectors before the loop and keep the references.