문제

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?

도움이 되었습니까?

해결책

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

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

다른 팁

Dereference the iterator, return it's address.

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

Also change from a const iterator.

 std::list<CCommandLineFlag>::iterator it
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top