Вопрос

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