2014-12-02 56 views
5

我正嘗試創建自己的翻譯器。這是大學工作。我需要在我的類翻譯器中使用迭代器。C++中的迭代器

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>

+0

順便說一句,你可能想打電話少的東西'translator'。只是爲了讓你的代碼更容易談論/推理。 ;) – Yakk 2014-12-02 10:06:21

回答

9

的映射的鍵是恆定的,因此該值類型是pair<const string, Word>

某些類型的別名可能使代碼更友好:

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

value_type &operator*(); 
+0

非常感謝你!有用 !! – Maverick94 2014-12-02 10:15:07

+0

這是一個相當容易犯的錯誤,並且是一個很好的例子,當不提倡明確提及該類型時。 – Lionel 2014-12-03 07:05:20

1

它比實際的答案補充,但如果你想要一個漂亮的迭代器(STL complient),你還需要添加幾個類型定義,以比如說你的迭代器的類型(在你的情況下你有一個輸入迭代器)。然後你可以使用你的迭代器和任何可以非常好的stl算法。然而,這可能非常麻煩。

一個非常好的方法是使用boost facade iterators,你只需要重寫需要三個方法的輸入迭代器來指定如何遞增,測試兩個迭代器是否相等和取消引用。然後Boost會爲您完成所有骯髒的工作,然後您可以使用符合標準的迭代器的所有stl算法。

下面是我給你的鏈接的示例:

# include <boost/iterator/iterator_facade.hpp> 
# include "node.hpp" 
class node_iterator : public boost::iterator_facade< 
    node_iterator 
    , node_base 
    , boost::forward_traversal_tag 
>{ 
public: 
node_iterator() 
    : m_node(0) {} 

explicit node_iterator(node_base* p) 
    : m_node(p) {} 
private: 
friend class boost::iterator_core_access; 

void increment() { m_node = m_node->next(); } 

bool equal(node_iterator const& other) const 
{ 
    return this->m_node == other.m_node; 
} 

node_base& dereference() const { return *m_node; } 

node_base* m_node; 
}; 
+0

儘管您的建議可能通常很有用,但它並不回答 – 2014-12-02 10:11:33

+0

這個問題你說得對,它更像是補充信息。我編輯了我的「答案」。 – geoalgo 2014-12-02 10:23:39