What's the most efficient way of iterating over one of several known ranges based on some condition?
pseudo-code for a binary condition:
for element in (condition ? range_a : range_b)
// do work
This 'example' shows my intention using a range-based for loop but as std::initializer_list
has reference semantics it won't work.
constexpr auto some_range(bool c) -> std::initializer_list<int> {
if (c) {
return {1,2};
} else {
return {3, 4, 5};
}
}
bool cond = true; // false
for(auto x : some_range(cond)) {
// things
}
yields: warning: returning address of local temporary object [-Wreturn-stack-address]
During run-time I could return a std::vector
but that would involve constructing a new vector every call:
auto some_range(bool c) -> std::vector<int> {
if (c) {
return {1,2};
} else {
return {3, 4, 5};
}
}
I could use a fixed size std::array
of std::optional<int>
but I would rather resort to a C++14 or c++11 solution.
Any help would be greatly appreciated.
Aucun commentaire:
Enregistrer un commentaire