0

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.

Michał Turek
  • 701
  • 3
  • 21

1 Answers1

1

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!
The Coding Fox
  • 1,488
  • 1
  • 4
  • 18
  • it does not work for me in vs enterprise 2019 – Michał Turek Mar 05 '22 at 10:14
  • i get compiler error: error C2429: language feature 'structured bindings' requires compiler flag '/std:c++17' – Michał Turek Mar 05 '22 at 10:21
  • 1
    @MichałTurek You need to set the language version to C++17. I assumed you had done so already, since you are specifically asking for a C++17 solution: https://stackoverflow.com/questions/41308933/how-to-enable-c17-compiling-in-visual-studio – user17732522 Mar 05 '22 at 10:34