Juce::enumerate is cool

Just saw it appear on develop, makes writing for loops a lot nicer when you need an index

        std::vector<int> foo = { 1, 2, 3, 4, 5 };

        for (auto [i, v] : juce::enumerate (foo))
            printf ("%ld at %d\n", i, v);

Now a feature request, reverse iterator?


Do you mean like std::make_reverse_iterator or something else?

Nice feature.

Are there potential drawbacks to performance?

Thank you for sharing this code, I was just looking the other day for documentation on format specifiers but I couldn’t find the right words, or examples in my own code!

Also… the enumerate example is neat too! :wink: I am still coming to terms with the auto keyword which seems like sheer magic especially here. This code couldn’t be any shorter if you wrote it in Python.

But yeah, I really was writing long, ugly chunks of code like this

        juce::String ci = static_cast<String>(i);
        juce::String sampleRateStr = static_cast<String>(sampleRate);
        DBG("C" + ci + " setting size with sample rate " + sampleRateStr);

just to format a simple string… forgive me :sob:

OT, but String::formatted() can be a nice thing…

String something = "myString";
char name[10] = "name";
int i = 0;
float f = 1.23f;
DBG(String::formatted("here is %s with %s with value %d, float %d", 
                name, something.getCharPointer(), i, f));
1 Like

Yes, very OT, I hope that is okay :sweat_smile:

If it helps I’ll throw in a :+1: for the feature request… the juce_Enumerate.h source is way beyond me, I have never used the operator keyword before and only have the barest understanding of templating so I can’t participate in that discussion much.

But it’s very helpful for me to pick up little things from eavesdropping on the advanced discussions so I hope that’s ok.

Thank you for sharing the juce String::formatted() operator, but I notice there are some warnings in the documentation about it? You avoided the strictest warning (“do not pass String objects as parameters”) but the full consequences are not clear to me…

I see none of that as any issue for using it for debugging printouts. The advantages are enormous for anyone used to using printfs and sprintfs… And it seems Jules was just philosophically opposed to it. :slight_smile:

1 Like

I mean the equivalent of this, except the indexes wouldn’t be wrong

        std::vector<int> vals = { 0, 1, 2, 3, 4 };
        for (auto [i, v] : juce::enumerate (std::views::reverse (vals)))
            printf ("vals[%d] = %d\n", int (i), v);

Is is supposed to work fine with temporary also (or is it dangling)?

for (auto [i, v] : juce::enumerate (getMyVector()))

If not, a warning should be added into the documentation.

Looks interesting. There is also std::views::enumerate coming in C++23.

1 Like