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

access c++ stl map only using iterator

本文关键字:c++stl 映射 访问 迭代器      更新时间:2023-10-16

我想要一个将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; }
}

在函数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();
}

问候J.

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

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
    }
}

简短的答案是否定的。您至少需要m_map.end()来结束循环。然而,我建议不要使用get_iterator(),而是在类中添加类似for_each的内容来接受std::function,并使用std::for_each将其应用于映射中的所有元素。这样一来,您的acton甚至不需要知道它迭代了映射,它只是完成了自己的工作。

您需要一个"开始"和一个"结束"来迭代它。

例如

class CTest{
private:
 std::map<int, int> m_map;
public:
 std::map<int int>::const_iterator cbegin();
 std::map<int int>::const_iterator cend();
 void add(int key, int val) { m_map[key] = val; }
}
void some_actoin()
{
 for(std::map<int int>::const_iterator it = c.cbegin(); it != c.cend(); ++it)
 {
     const auto& val = *it;
 }
 // C++11
 for(const auto& val : c)
 {
 }
}