Below is text from Scott Meyers Effective STL regarding iterators Item 26.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" id="chk1" value="1" class="chk" onclick="CheckBox(this)" />1
<input type="checkbox" id="chk2" value="2" class="chk" onclick="CheckBox(this)" />2
<input type="checkbox" id="chk3" value="3" class="chk" onclick="CheckBox(this)" />3
<input type="checkbox" id="chk4" value="4" class="chk" onclick="CheckBox(this)" />4
<input type="button" id="btn" value="alert" />
</div>
All we're doing here is comparing two iterators into a container, the kind of comparison that's the bread and butter of the STL. The only twist is that one object is of type iterator and one is of type const_iterator. This should be no problem. The iterator should be implicitly convened into a const_iterator. and the comparison should be performed between two const_iterators.
With well-designed STL implementations, this is precisely what happens, but with other implementations, the code will not compile. The reason is that such implementations declare operator== for const_iterators as a member function instead of as a non-member function, but the cause of the problem is likely to be of less interest to you than the workaround, which is to swap the order of the iterators, like this:
typedef deque<int> IntDeque; //STL container and
typedef lntDeque::iterator Iter; // iterator types are easier
typedef lntDeque::const_iterator Constlter; // to work with if you
// use some typedefs
Iter i;
Constlter ci;
… //make i and ci point into
// the same container
if (i == ci ) ... //compare an iterator
// and a const_iterator
My question on above
答案 0 :(得分:4)
The issue here is that the comparison operators compare C'.X^2 + C'.Y^2 = LenA^2
with iterator
and iterator
with const_iterator
. If the operators are non-member functions the compiler will find the conversion from const_iterator
to iterator
and call the const_iterator
comparison function. If the comparison operator is a member function it will be called on the lhs which, in the example, is an const_iterator
and there is no way to convert a iterator
to an const_iterator
. What the workaround does is to put the iterator
as lhs and since const_iterator
can be converted to iterator
the comparison compiles.