将stl :: vector迭代器条目传递给函数

时间:2018-07-13 09:10:51

标签: c++ vector

我有以下定义:

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;

using PublisherAssignments = std::vector<S_DEMO_ENTRY_ASSIGN>;

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.
    PublisherAssignments  vectorItemAssignFuture; // Sorted array of S_DEMO_ENTRY_ASSIGN structures (future on active schedule).
} S_DEMO_ENTRY_EX;

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

我有这张地图:

PublisherMap m_mapPublishers;

我正在反向迭代发布者的工作:

for (auto & m_mapPublisher : m_mapPublishers)
{
    for (auto iterAssign = m_mapPublisher.second.vectorItemAssign.rbegin();
        iterAssign != m_mapPublisher.second.vectorItemAssign.rend(); iterAssign++)
    {
        S_DEMO_ENTRY_ASSIGN sDemoEntryAssign = *iterAssign;
        bool bValidAssignment = GetMostRecentDateForAssignment(m_eAssignmentContext, sDemoEntryAssign);
        // ...
    }
}

以前,我只是使用iterAssign->访问结构值,但是我决定将内部for循环的代码移到方法中。我弄清楚如何将结构iterAssign传递到方法中的唯一方法是首先将其复制。

还有另一种方法可以将vectore迭代器条目传递给函数吗?

1 个答案:

答案 0 :(得分:1)

是的,您可以通过引用传递值:

S_DEMO_ENTRY_ASSIGN &sDemoEntryAssign = *iterAssign;

或简单地:

bool bValidAssignment = GetMostRecentDateForAssignment(m_eAssignmentContext, *iterAssign);

只需确保您的GetMostRecentDateForAssignment方法通过引用将其参数除外:

GetMostRecentDateForAssignment(..., const S_DEMO_ENTRY_ASSIGN &sDemoEntryAssign)

注意:我将其作为const引用,因为似乎该方法并非旨在更改sDemoEntryAssign的值。