【发布时间】:2021-07-12 03:14:30
【问题描述】:
我正在尝试在公共成员函数中迭代作为我的类的私有成员的 multimap,以便我可以遍历 multimap 并打印元素。我知道如果我使打印函数低于非常量它可以工作,但我不能完全理解为什么它不能与 const 一起工作。我假设分配迭代器(my_map.begin())允许修改multimap,但const修饰符不允许这样做,因此代码将无法编译。谁能给我一个清晰和更深入的解释至于为什么这不适用于 const 函数?我对使用 STL 容器还很陌生,只是想更好地了解它们的功能。感谢所有和任何帮助。 (下面的 C++ 代码) (P.S. 为了尽可能清楚,我不是在问如何迭代多图。再次感谢。)
#include <iostream>
#include <iterator>
#include <string>
#include <map>
// Synonymous types for my multimap and multimap iterator
typedef std::multimap<int, std::string> mm;
typedef mm::iterator mit;
class Foo
{
private:
mm my_map;
static int count;
public:
Foo() {}
void add(const std::string&);
void print() const;
};
int Foo::count = 0;
void Foo::add(const std::string& s)
{
my_map.insert(std::make_pair(count++, s));
}
**// This is the implementation of the that breaks my code**
void Foo::print() const
{
mit it = my_map.begin(); // **I do not fully understand why this does not work.**
}
【问题讨论】:
标签: c++ stl iterator constants multimap