foreach 循环中的结构化绑定

Structured bindings in foreach loop

考虑代码的休闲和平:

using trading_day = std::pair<int, bool>;
using fun_intersection = vector<pair<int, bool>>;
double stock_trading_simulation(const fun_vals& day_value, fun_intersection& trade_days, int base_stock_amount = 1000)
{
    int act_stock_amount = base_stock_amount;
    for(auto trade  : trade_days)
    {
        if (trade.second == BUY)// how to change it to trade.action?
        {

        }
        else
        {

        }
    }
}

我想做的不是将 pair 称为 .first.second 我想将它们称为 .day 和 .action,是吗有可能以任何实用的方式使用 c++17 或更早的版本吗?

我试过这样做:

for(auto[day,action] trade  : trade_days)

但是它无法编译。

正如 user17732522 所说,您可以将 range-based for loops 用于此目的:

#include <iostream>
#include <vector>

using trading_day = std::pair<int, bool>;
using fun_intersection = std::vector<std::pair<int, bool>>;

int main()
{
    fun_intersection fi({ {1, true}, {0, true}, {1, false}, {0, false} });
    for (auto& [day, action] : fi)
    {
        if (day == 1 && action == true) std::cout << "Success!" << std::endl;
        else std::cout << "Fail!" << std::endl;
    }
}

输出:

Success!
Fail!
Fail!
Fail!