2011-01-26 32 views
2

如果我已經構建了一個我想包含在內部的類,例如一個集合,我將如何迭代所述集合?我可以說迭代器的自定義對象的容器

std::set<customObject>::iterator it 

我想我能做到這一點,但我發現了以下一系列的錯誤...

drawing.h:110: error: no match for ‘operator=’ in ‘it = ((object*)this)->object::objects. std::vector<_Tp, _Alloc>::begin [with _Tp = object, _Alloc = std::allocator<object>]()’ 
/usr/include/c++/4.2.1/bits/stl_tree.h:225: note: candidates are: std::_Rb_tree_const_iterator<object>& std::_Rb_tree_const_iterator<object>::operator=(const std::_Rb_tree_const_iterator<object>&) 
drawing.h:110: error: no match for ‘operator!=’ in ‘it != ((object*)this)->object::objects. std::vector<_Tp, _Alloc>::end [with _Tp = object, _Alloc = std::allocator<object>]()’ 
/usr/include/c++/4.2.1/bits/stl_tree.h:292: note: candidates are: bool std::_Rb_tree_const_iterator<_Tp>::operator!=(const std::_Rb_tree_const_iterator<_Tp>&) const [with _Tp = object] 
drawing.h:111: error: ‘struct std::_Rb_tree_const_iterator<object>’ has no member named ‘sketch’ 

這裏是我的代碼:

void draw_in_place() 
     { 
      place(); 
      std::set<object>::const_iterator it; 
      for(it = objects.begin(); it != objects.end(); it++){ 
       *it.draw_in_place(); 
      } 
     } 

回答

4
((object*)this)->object::objects. std::vector<_Tp, _Alloc>::begin 

objects顯然是std::vector<object>,而不是std::set<object>。因此您需要使用std::vector<object>::const_iterator

*it.draw_in_place(); 

這是不正確的:你需要提領迭代器首先訪問的元素,然後使用元素:

(*it).draw_in_place(); 
// or 
it->draw_in_place(); 
+0

`it-> draw_in_place()` – 2011-01-26 05:18:20

+0

@Fred:是的,或者您可以使用` - >`。 (我總是使用`(* it).`來代替迭代器的`it->`。不要問爲什麼:我不知道,我認爲它使得迭代器的使用更突出一點,但這是隻有個人意見) – 2011-01-26 05:21:46

2

我認爲(至少)你的問題之一是這一行:

*it.draw_in_place(); 

編譯器解釋本作爲

*(it.draw_in_place()); 

與您的預期

(*it).draw_in_place(); 

爲了解決這個問題,可以考慮使用箭頭運算符,如

it->draw_in_place(); 

這是完全合法的存儲自定義在STL集合對象,只要他們能比與<運算符默認。如果他們不能,您需要在其上定義operator <,或者爲set提供自定義比較器,或者爲您的特定類型專門提供std::less