BarsMonster
BarsMonster

Reputation: 6583

C++ : elegantly iterate a set of numbers

Could anyone suggest how in C++11/14 to elegantly iterate a constant set (in english meaning, not C++ meaning) of numbers, preferably without leaving temporary objects like here:

set<int> colors;
colors.insert(0);
colors.insert(2);

for (auto color : colors)
{
    //Do the work
}

? Hope to find a 1-liner.

In other words, is there a magical way to make it look somewhat like this:

for (int color in [0,2])//reminds me of Turbo Pascal
{
    //Do the work
}

or

for (auto color in set<int>(0,2))//Surely it cannot work this way as it is
{
    //Do the work
}

Upvotes: 0

Views: 106

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41840

You can use std::initializer_list instead of a std::set:

for (auto color : {2, 5, 7, 3}) {
    // Magic
}

The enclosed braces { ... } will deduce an std::initializer_list<int>, which is iterable.

Upvotes: 3

phg1024
phg1024

Reputation: 179

Just some random thoughts. Something like this?

for(auto color : set<int>{0, 2}) { // do the work }

Or maybe use a function?

auto worker = [](int x) { // do the work };
worker(0);
worker(2);

To avoid temporary object, maybe use templated function like

template<int N>
void worker(params_list) {
   // do the work
}

then

worker<0>(params_list);
worker<2>(params_list);

Upvotes: 1

Related Questions