c++c++17structured-bindings

Structured bindings in foreach loop


Consider fallowing peace of code:

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
        {

        }
    }
}

What I would like to do is to instead of referring to pair as .first and .second I would want to refer to them as .day and .action, is it possible in any practical way to use c++17 or earlier versions?

I tried doing something like this:

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

however it does not compile.


Solution

  • As said by user17732522, you can use range-based for loops for this purpose as such:

    #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;
        }
    }
    

    Output:

    Success!
    Fail!
    Fail!
    Fail!