If you need to use the variables relevantGamesGroup and numberOfGroups after only having checked the condition once, you could create and call a temporary lambda that you make return the necessary pair:
auto&& [relevantGamesGroup, numberOfGroups] =
[&]() -> std::pair<std::vector<std::vector<int>>&, int>
{
if (useGroups) return {objFlight.gamesGroup[dayIndex],
objFlight.numberOfGroups[dayIndex]};
return {objFlight.gamesSubGroups[dayIndex],
2 * objFlight.numberOfGroups[dayIndex]};
}();
// use relevantGamesGroup and numberOfGroups here
An alternative using the ternary/conditional operator instead of using a lambda:
auto&& [relevantGamesGroup, numberOfGroups] =
useGroups ? std::pair<std::vector<std::vector<int>>&, int>
{objFlight.gamesGroup[dayIndex],
objFlight.numberOfGroups[dayIndex]}
: std::pair<std::vector<std::vector<int>>&, int>
{objFlight.gamesSubGroups[dayIndex],
2 * objFlight.numberOfGroups[dayIndex]};
// use relevantGamesGroup and numberOfGroups here
If you use this kind of construct a lot, creating a helper function could simplify it:
#include <tuple>
template<class... Ts>
std::tuple<Ts...> ternary(bool cond, std::tuple<Ts...>&& True,
std::tuple<Ts...>&& False) {
return cond ? True : False;
}
You'd then supply the wanted types as template parameters and use structured bindings to extract the selected values / references just like above:
int main() {
int a1 = 1, b1 = 2, c1 = 3;
int a2 = 40, b2 = 50, c2 = 60;
auto&&[a,b,c] = ternary<int&,int&,int&>(true, {a1,b1,c1}, {a2,b2,c2});
std::cout << a << b << c << '\n';
++a; ++b; ++c; // these are references to a1, b1 and c1
std::cout << a1 << b1 << c1 << '\n';
}
Output:
123
234
With the types in your question, it could look like this:
void func(bool useGroups) {
auto&& [relevantGamesGroup, numberOfGroups] =
ternary<std::vector<std::vector<int>>&, int>(useGroups,
{objFlight.gamesGroup[dayIndex], objFlight.numberOfGroups[dayIndex]},
{objFlight.gamesSubGroups[dayIndex], 2 * objFlight.numberOfGroups[dayIndex]});
// use relevantGamesGroup and numberOfGroups here
}
numberOfGroups = (useGroups ? 2 : 1) * objFlight.numberOfGroups[dayIndex];but this is arguably less clear, and may be slightly less efficient, depending on how the compiler optimizes.2 *line? Should it useSubGroupsthere?objFlight.numberOfGroups[dayIndex] * (useGroups + 1)if you really want to be a smartass :)