2012-01-03 32 views
1

我有一個PROFESOR類此屬性附加傷害的push_back的向量的對象

vector<int> hDisponibles; 

如果我有這個類的一個載體

set<profesor> profesores; 

我試試這個

set<profesor>::iterator itP; 
itP = profesores.begin();  
while (itP != profesores.end()){     
    (*itP).hDisponibles->push_back(0);              
    itP++; 
} 

但是這個錯誤

utils.cpp:138: error: passing ‘const std::vector<int, std::allocator<int> >’ as ‘this’  argument of ‘void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]’ discards qualifiers 
+1

什麼是什麼錯誤'hDisponibles' – 2012-01-03 22:26:30

+1

請出示錯誤 – Lou 2012-01-03 22:27:05

回答

3

您的問題是您嘗試撥打push_backvectorconst。這是因爲(自C++ 11以來)通過const_iterators訪問std::set的元素,因爲更改它們可能會改變它們的比較方式並因此破壞set。爲了解決這個,你有兩種選擇:

  1. 如果hDisponibles對如何profesor比較沒有影響,它不會做你的整體結構的傷害,你可以聲明它mutable這樣的:mutable vector<int> hDisponibles;mutable成員即使它們存在於結構const
  2. 我這不是一個選項進行更改,你必須從一組(到臨時)刪除profesor,做你push_back,然後重新插入(小心迭代器無效)。當然這是非常昂貴的。

你張貼的代碼有一個額外的錯誤,因爲hdisponsibles是一個對象,但push_back被稱爲如果它是一個指針。從您的compilermessage它似乎並不喜歡這個bug是在你的實際代碼,但以防萬一它應該是:

(*itP).hDisponibles.push_back(0);  

編輯:發現在標準草案的部分(該值類型是一樣的作爲鍵setmultiset:??N3290§23.2.4/ 6

iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type. [Note: iterator and const_iterator have identical semantics in this case, and iterator is convertible to const_iterator. Users can avoid violating the One Definition Rule by always using const_iterator in their function parameter lists. —endnote ]

+0

或者不是(2),您可以重寫整個循環,以便構建一組全新的修改結果。 – 2012-01-03 23:56:03

+0

或者,如果hDisponibles是一個指針,那麼就不必擔心const/mutable的東西(只要它不是const的指針) – 2012-01-04 06:57:43

1

與您的代碼的明顯的錯誤是,你在這條線使用->代替.

(*itP).hDisponibles->push_back(0); // should be itP->hDisponibles.push_back(0); 

但我有一種感覺有什麼地方語法有關更多的錯誤。請發佈更完整的代碼摘要以及您收到的錯誤。

+0

有(* ITP).hDisponibles->的push_back(0) 。錯誤:' - >'的基本操作數具有非指針類型'const std :: vecto r >' – JuanPablo 2012-01-03 22:31:00

4

std::set只提供常量迭代器,因爲修改它們在集合中的對象會破壞集合的不變性。所以,你不能用std::set做你想要的,你需要讀取新的對象,或者使用不同的容器。

+1

好吧,它是'std :: vector',所以它不是const。 – 2012-01-03 22:37:45