将结构添加到 std::map

Adding a structure into a std::map

我已经看到这个问题 (What is the preferred/idiomatic way to insert into a map?) 并且可以像这样填充我的地图:

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

是否可以插入结构而不必首先创建实际的 SPECIAL_EVENT_S 变量?这可以嵌入到 insert 函数调用中吗?


SPECIAL_EVENT_S结构定义:

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

重现

MFC 对话框应用程序

对话框header:

#include <map>

using SPECIAL_EVENT_S = struct tagSpecialEvent
{
    CString         strEvent;
};

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

添加私有成员变量:

private:
    SpecialEventDataMap m_mymap;

在对话框中 OnInitDialog:

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

不会工作。

你可以使用 C++20 designated initializers:

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

可以在map中默认构建,然后填充:

auto& sEvent = m_mapSpecialEvents[datEvent.Format(_T("%Y-%m-%d"))];

sEvent.datEvent = datEvent; sEvent.strEvent = strDescription; sEvent.strLocation = strLocation;