thedafferg
thedafferg

Reputation: 99

How to iterate over a multimap to satisfy an IF condition - C++

I have two multimaps, one with Dates and floats, the other with Times and floats. Both maps have duplicate values. In the multimap with dates as keys, i iterate over it and store the maximum float value for a date that was entered by the user. Then, in my next map I want to retrieve the times for the date where this value exists. (All my data comes from a vector holding all these values I need). My goal is to print out the times that have the maximum float value for a date, so it could be at one time or more.

Currently, my program prints out all the times that hold that float value, including the times that do not belong to the date the user entered. How do i fix my logic so that i only retrieve the times that have the user's entered date, as well as the maximum value?

Code:

float maxVal = 0;
    for(std::multimap<Date, float>::iterator it = mapOption5Solar.begin(); it!=mapOption5Solar.end(); it++)
    {
        if(checkDate == it->first)
        {
            if(maxVal < it->second)
            {
                maxVal = it->second;
            }

        }
    }




    for(std::multimap<Time, float>::iterator it = mapOption5Time.begin(); it != mapOption5Time.end(); it++)
    {
        if(maxVal == it->second)
        {
            timeVec.add(it->first);
        }
    }

Upvotes: 0

Views: 458

Answers (1)

Anton Shwarts
Anton Shwarts

Reputation: 525

If Date and Time are not connected, then in no way. You cannot match time to a specific date.

I would recommend creating a structure, like below and store your data in multimap<DateTime, float>

struct DateTime {
    Date date;
    Time time;
};

Afterwards you can write

float maxVal = 0;
for(const auto& [dateTime, value] : mapOption5)
{
    if(checkDate == dateTime)
    {
        if(maxVal < value)
        {
            maxVal = value;
        }
     }
}

for(const auto& [dateTime, value] : mapOption5)
{
    if((checkDate == dateTime) && (maxVal == value)
    {
        timeVec.add(value);
    }
}

Upvotes: 1

Related Questions