2012-07-12 100 views
3

我試圖做到這一點:初始化一個std ::地圖迭代器類成員

typedef std::map<std::string, time_t> my_map; 
const mymap& some_function(); 

class bla 
{ 
private: 
    my_map::iterator current 
    bla(const mymap& m) : current(m.begin()) 
    { } 
} 

而且它不工作。有點比較繞口真正的錯誤消息是:

error: no matching function for call to 'std::_Rb_tree_iterator, long int> >::_Rb_tree_iterator(std::map, long int>::const_iterator)'

我嘗試了初始化/分配移動到構造函數體:

{ current = m.begin(); } 

這也不能工作。因此,我認爲,中current類型是錯誤的,所以我只是讓編譯器推斷出:

... 
    decltype(my_map::begin()) current; 
... 

這也不起作用。

所有我需要的是設定在bla施工時間迭代器的成員,所以我沒有明確設置它在一些愚蠢的額外功能,並可以在地圖上通過外部迭代:

bool bla::do_stuff(...output...) 
{ 
    if(current = m.end()) 
     return false; 
    balblabla(current); 
    ++current; 
    return true; 
} 

回答

6

您正試圖將const_iterator指定爲iterator。有兩種解決方案:

  1. 以非常量參考(bla(my_map& m) : current(m.begin()) {})拍攝地圖。
  2. 將會員類型更改爲const_iterator
4

在一個const情況下,你只能獲得const_iterator

my_map::const_iterator current; 
bla(const my_map & m) : current(m.begin()) { } 

如果你想有一個非const迭代器,你必須構建從非恆定的參考您的bla對象。