C++ typedef, map, iterator

C++ typedef, map, iterator

本文关键字:iterator map C++ typedef      更新时间:2023-10-16

有人能帮我解决迭代器问题吗?我有这样的东西:

class SomeClass{
public:
    //Constructor assigns to m_RefPtr a new t_Records
    //Destructor deletes m_RefPtr or decreases m_RefCnt
    //Copy Constructor assigns m_RefPtr to new obj, increases m_RefCnt
    bool Search(const string &);
private:
    //Some private variables
    struct t_Records{ //For reference counting
        int m_RefCnt; //Reference counter
        typedef vector<int> m_Vec;
        typedef map<string, m_Vec> m_Map;
        m_Map m_RecMap;
        t_Records(void){
            m_RefCnt = 1;
        }
    };
    t_Records * m_RefPtr;
};
//Searchs through the map of m_RefPtr, returns true if found
bool SomeClass::Search(const string & keyword){
    //How to create and use an iterator of m_Map???
    return true;
}

正如我所提到的,我在结构之外创建(定义)映射迭代器时遇到了麻烦。映射已初始化并包含一些记录。谢谢你的回复。

像这样:

// assuming m_RefPtr is properly initialized:
t_Records::m_Map::iterator it = m_RefPtr->m_RecMap.begin();
++it; // etc.

顺便说一下,m_Map对于一个类型来说是个坏名字。按照惯例,以m_为前缀的名称用于数据成员。

您可以像这样迭代

for (m_Map::iterator it = m_RecMap.begin(); it != m_RecMap.end(); ++it)
{
    // do stuff with *it
}

或者更简单的

for (auto it = m_RecMap.begin(); it != m_RecMap.end(); ++it)
{
    // do stuff with *it
}