Storing std::map iteration object as itemdata in C

2019-09-14 17:24发布

I have been trying to decide how to convey my problem.

I have some maps:

typedef struct tagDemoEntryAssign
{
    COleDateTime datMeeting;
    CString      strAssignment;
    int          iAssignmentType; // AJT v16.0.9
    int          iStudyPoint;     // AJT v16.0.3
    int          iNextStudyPoint; // AJT v16.0.9
} S_DEMO_ENTRY_ASSIGN;

typedef std::vector<S_DEMO_ENTRY_ASSIGN> PublisherAssignments;

typedef struct tagDemoEntryEx
{
    CString     strName;
    E_GENDER    eGender;
    E_POSITION  ePosition;
    E_APPOINTED eAppointed;
    BOOL        bDemonstrations; // AJT v16.0.3

    PublisherAssignments  vectorItemAssign; // Sorted array of S_DEMO_ENTRY_ASSIGN structures.
} S_DEMO_ENTRY_EX;

typedef std::map<CString, S_DEMO_ENTRY_EX> PublisherMap;
typedef std::map<CString, S_DEMO_ENTRY_EX>::iterator PublisherMapIter;

I end up having some data, and filling in a CGridCtrl. I try to set the item data for the cells. Specifically:

m_Grid.SetItemData(iRowCount - 1, DEMO_COLUMN_NAME, (LPARAM)&iter->second);

When I try to access the LPARAM data is it not valid.

Why?

Update

I think the problem is related to this line of code:

S_DEMO_ENTRY_ASSIGN sAssign = iter->second.vectorItemAssign.back();

I assign it as item data:

m_Grid.SetItemData(iRowCount - 1, DEMO_COLUMN_LAST_USED, (LPARAM)&sAssign);

It subsequently gets used here:

int CALLBACK CDemoPickerDlg::pfnCellCompareDate(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
    CGridCellBase* pCell1 = (CGridCellBase*)lParam1;
    CGridCellBase* pCell2 = (CGridCellBase*)lParam2;
    if (!pCell1 || !pCell2) return 0;

    S_DEMO_ENTRY_ASSIGN *psItem1 = (S_DEMO_ENTRY_ASSIGN*)pCell1->GetData();
    S_DEMO_ENTRY_ASSIGN *psItem2 = (S_DEMO_ENTRY_ASSIGN*)pCell2->GetData();

    // If a name has never been used the structure pointer will be null.
    if (psItem1 == NULL && psItem2 == NULL)
        return 0;
    else if (psItem1 == NULL)
        return -1;
    else if (psItem2 == NULL)
        return 1;
    else if (psItem1->datMeeting < psItem2->datMeeting)
        return -1;
    else if (psItem1->datMeeting == psItem2->datMeeting)
        return 0;
    else
        return 1;

}

I think that this is wrong:

S_DEMO_ENTRY_ASSIGN sAssign = iter->second.vectorItemAssign.back();

If I understand the mechanics right, the above is making a copy of the structure. Then I am assigning the pointer of this copy. And the copy goes out of scope in the iteration loop of the map.

I need to store a pointer to the actual iter->second.vectorItemAssign.back() object instead I think.

1条回答
时光不老,我们不散
2楼-- · 2019-09-14 17:48

I had to change one line of code to:

m_Grid.SetItemData(iRowCount - 1, DEMO_COLUMN_LAST_USED, (LPARAM)&iter->second.vectorItemAssign.back());
查看更多
登录 后发表回答