Search code examples
visual-c++c++17structurestdmapvisual-studio-2022

Adding a structure into a std::map


I have seen this question (What is the preferred/idiomatic way to insert into a map?) and can populate my map like this:

SPECIAL_EVENT_S sEvent{};

sEvent.datEvent = datEvent;
sEvent.strEvent = strDescription;
sEvent.strLocation = strLocation;
sEvent.iForeignLanguageGroupMenuID = dwForeignLanguageGroup;
sEvent.eSRREventType = static_cast<EventTypeSRR>(dwEventTypeSRR);
sEvent.eMWBEventType = static_cast<EventTypeMWB>(dwEventTypeSMR);

// Duration
sEvent.datEventStartTime = datEventStartTime;
sEvent.datEventFinishTime = datEventFinishTime;
sEvent.bEventAllDay = bEventAllDay;

// Reminder
sEvent.bSetReminder = bSetReminder;
sEvent.iReminderUnitType = iReminderUnitType;
sEvent.iReminderInterval = iReminderInterval;

// Videoconference events
sEvent.iImageWidthPercent = wImageWidthPercent;
sEvent.strImagePath = strImagePath;
sEvent.strTextBeforeImage = strTextBeforeImage;
sEvent.strTextAfterImage = strTextAfterImage;
sEvent.eType = eType;

m_mapSpecialEvents.insert(
    {
        datEvent.Format(_T("%Y-%m-%d")),
        sEvent
    }
);

Is it possible to insert the structure without having to create an actual SPECIAL_EVENT_S variable first? Can this be embedded into the insert function call?


SPECIAL_EVENT_S structure definition:

using SPECIAL_EVENT_S = struct tagSpecialEvent 
{
    COleDateTime    datEvent;
    CString         strEvent;
    CString         strLocation;

    // Foreign Language Group
    EventTypeSRR    eSRREventType{};
    EventTypeMWB    eMWBEventType{};
    int             iForeignLanguageGroupMenuID{};

    // Duration
    COleDateTime    datEventStartTime;
    COleDateTime    datEventFinishTime;
    BOOL            bEventAllDay{};

    // Reminder
    BOOL            bSetReminder{};
    int             iReminderUnitType{};
    int             iReminderInterval{};

    // Videoconference events
    int             iImageWidthPercent{};
    CString         strImagePath;
    CString         strTextBeforeImage;
    CString         strTextAfterImage;
    CChristianLifeMinistryDefines::VideoConferenceEventType eType{};
};

To reproduce

MFC Dialog app

Dialog header:

#include <map>

using SPECIAL_EVENT_S = struct tagSpecialEvent
{
    CString         strEvent;
};

using SpecialEventDataMap = std::map<CString, SPECIAL_EVENT_S>;

Add a private member variable:

private:
    SpecialEventDataMap m_mymap;

In the dialog OnInitDialog:

m_mymap.insert(_T("1234-56-78"), { .strEvent });

Will not work.


Solution

  • You can use C++20 designated initializers:

    m_mapSpecialEvents.insert(
        {
            datEvent.Format(_T("%Y-%m-%d")),
            {
              .datEvent = datEvent,
              .strEvent = strDescription,
              .strLocation = strLocation,
              // ...
              .eType = eType
            }
        }
    );