Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++98 v. C++11 std::set::insert Specifications

Tags:

c++

c++11

The meaning of the iterator passed as a position hint to std::set::insert(iterator position, const value_type& val) and std::multiset::insert(iterator position, const value_type& val) changes between C++98 and C++ 11. Is there an easy way at compile-time to detect which is in use and use different code?

A general check on C++11 does not appear to be a good idea (1, 2), and I didn't see a suitable Boost.Config macro.

Specifically, the documentation for C++98 says:

The function optimizes its insertion time if position points to the element that will precede the inserted element.

while for C++11 it says:

The function optimizes its insertion time if position points to the element that will follow the inserted element (or to the end, if it would be the last).

This matters because the hint effects the complexity of the insertion call. If the hint is correct, the complexity is only an amortized constant. But if it's not, it's logarithmic in size.

Update

As so nicely described below by JerryCoffin, the C++98 specification is, essentially, a typo.

like image 592
Jon Avatar asked Aug 11 '14 19:08

Jon


1 Answers

This was the subject of a defect report, LWG issue #233, and n1780.

As noted there, it was apparently a simple error in editing the C++98 standard.

Stepanov's original implementation worked according to the current specification, and as far as I know most (all?) implementations since have done the same (though there is one that looks both before and after the hinted location, so you'll get optimal behavior if you specify either one).

This also makes it possible to hint that an insertion will be at the beginning of the set, which wasn't possible under the previous specification.

like image 179
Jerry Coffin Avatar answered Oct 05 '22 19:10

Jerry Coffin