Search code examples
c++stlstdlist

Accessing the Item Found by std::find()


I'm trying to teach myself the Standard Template Library. Currently, I'm using std::find() to search a std::list.

I have code that tests if an item exists and it seems to work just fine.

inline bool HasFlag(TCHAR c)
{
    std::list<CCommandLineFlag>::const_iterator it = std::find(m_Flags.begin(), m_Flags.end(), c);
    return (it != m_Flags.end());
}

However, this version, which is supposed to return the matching element, does not compile. I get the error message "error C2446: ':' : no conversion from 'int' to 'std::_List_const_iterator<_Mylist>'".

inline CCommandLineFlag* GetFlag(TCHAR c)
{
    std::list<CCommandLineFlag>::const_iterator it = std::find(m_Flags.begin(), m_Flags.end(), c);
    return (it != m_Flags.end()) ? it : NULL;
}

How can I return a pointer to the instance of the matching item in the second version?


Solution

  • You need to take the address of the item referenced by the iterator:

    return (it != m_Flags.end()) ? &(*it) : NULL;