2012-01-03 46 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