Jun 23, 2009

GCC Does Not Support Mutable Set/MultiSet Iterator

Although C++ STL standard requires that std::set and set::multiset supports both constant iterator and mutable iterator, but libstdc++ supports only the constant one. In /usr/include/c++/4.0.0/bits/stl_set.h (as well stl_multiset.h), we can see the following iterator typedefs:
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// DR 103. set::iterator is required to be modifiable,
// but this allows modification of keys.
typedef typename _Rep_type::const_iterator iterator;
typedef typename _Rep_type::const_iterator const_iterator;
This would lead many STL algorithms incompatible with set and multiset. For example, the following code does not compile in GCC 4.0.x:
set myset;             // or multiset myset;
*myset.begin() = 100; // fails due to begin() returns const_iterator
remove_if(myset.begin(), myset.end(), Is71()); // remove_if invokes remove_copy_if, which requires mutable myset.begin().
It is notable that Microsoft Visual C++ 7.0 and later versions are more restrictive to the STL standard on above issue. Above code works with Visual C++.

1 comment:

test said...

It took me few hours to understand why remove_it() doesn't work with multiset before I have found this post.