Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading