仅使用迭代器访问c ++ stl映射

Jos*_*siP 0 c++ stl

我希望有一个带有map变量的类作为私有变量:

class CTest{
private:
 std::map<int, int> m_map;
public:
 std::map<int int>::iterator get_iterator();
 void add(int key, int val) { m_map[key] = val; }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在函数中some_action()我只能get_iterator()在地图上使用迭代,例如:

CTest c;

/* here i want to go through that m_map, but i cannot have access to it */
void some_actoin(){
 ???
}

int main(void){
  c.add(1, 1);
  c.add(2, 3);
  some_action();
}
Run Code Online (Sandbox Code Playgroud)

关于J.

Jon*_*ter 6

如果你真的想这样做,你可以添加公共方法来获得开始和结束迭代器,例如

class CTest{
private:
    std::map<int, int> m_map;
public:
    std::map<int, int>::const_iterator cbegin() { return m_map.cbegin(); }
    std::map<int, int>::const_iterator cend() { return m_map.cend(); }
};

CTest c;

void some_action()
{
    for (std::map<int, int>::const_iterator it = c.cbegin(); it != c.cend(); ++it)
    {
        // do action
    }
}
Run Code Online (Sandbox Code Playgroud)