user2443456
user2443456

Reputation: 199

Inline array declaration with direct access in c++

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.

Upvotes: 1

Views: 2229

Answers (2)

LogicStuff
LogicStuff

Reputation: 19607

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.

Upvotes: 2

Hakes
Hakes

Reputation: 621

Creating an object like {"pierre", "paul", "jean"} results in a initializer list. Initializer list does not have any [] operator Why doesn't `std::initializer_list` provide a subscript operator?. So you should convert to const auto& author = (std::vector<std::string>{"pierre", "paul", "jean"})[i];. Also the reference symbol should not be there as you are creating a temporary object and you are storing a reference to a temporary.

Upvotes: 1

Related Questions