任何人都可以帮我解决迭代器问题吗?我有这样的事情:
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;
}
正如我所提到的,我在构造之外创建(定义)map迭代器时遇到了麻烦。地图是初始化的,包含一些记录。谢谢你的回复。
答案 0 :(得分:3)
像这样:
// assuming m_RefPtr is properly initialized:
t_Records::m_Map::iterator it = m_RefPtr->m_RecMap.begin();
++it; // etc.
顺便说一下,m_Map
是一个类型的错误名称。按照惯例,前缀为m_
的名称用于数据成员。
答案 1 :(得分:1)
您可以像这样迭代
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
}