c++ - C++ 中的迭代器

标签 c++ c++11 iterator overloading operator-keyword

我正在尝试创建自己的翻译器。这是大学作业。我的类翻译器中需要一个迭代器。

class Translator
{
private:
    map <string,Word> translator;

public:
    class iterator
    {
       friend class Translator;
        private:
            map<string,Word>::iterator itm;

        public:
            iterator operator++();
            pair <string,Word> &operator*();
            bool operator==(const iterator &it)const;
    };
};

我正在尝试重载 operator*() ;

这是代码。

pair <string, Word>& Translator::iterator::operator*()
{
  return (*itm);
}

错误:

invalid initialization of reference of type ‘std::pair<std::basic_string<char>, Word>&’ from expression of type ‘std::pair<const std::basic_string<char>, Word>

最佳答案

映射的键是常量,所以值类型是pair<const string, Word> .

某些类型别名可能会使代码更友好:

typedef map <string,Word> map_type;
typedef map_type::value_type value_type;

value_type &operator*();

关于c++ - C++ 中的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27245982/

相关文章:

c++ - 使用N-API时如何避免段错误?

c++ - 读取文件,尝试返回二维字符数组

c++ - 伪单例类的多个实例

c++ - 为什么类不能从 decltype 的结果继承?

multithreading - thread_guard 相当于 lock_guard/unique_lock

c++ - 如何返回对自定义容器中数据的对引用?

c++ - 带三个参数的 std::move - 通过复制传递的迭代器

java - 如何在迭代时从 "ConcurrentModificationException"中删除元素时避免 `ArrayList`?

c++ - 这个 StackOverFlowException 是否需要指针才能正常工作?

c++ - 如何在 iOS 中添加带有 PCM 数据/缓冲区的可播放(例如 wav、wmv) header ?