Prev: Code Optimization
Next: goto
From: Ralf Fassel on
Lately I stumbled upon operator> in this context:

std::vector<int> container(10);
// filling vector omitted
std::vector<int>::iterator itr = std::lower_bound(container.begin(), container.end(), somevalue);
if (itr > container.begin()) { ... }

This compiled w/o problems, but since we use operator != in loops (as
compared to <), I wondered whether using operator> is the Right Thing
here, and if it would not be better to use

if (itr != container.begin()) { ... }

Opinions?
R'

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Nick Hounsome on
On 19 Dec, 00:44, Ralf Fassel <ralf...(a)gmx.de> wrote:
> Lately I stumbled upon operator> in this context:
>
> std::vector<int> container(10);
> // filling vector omitted
> std::vector<int>::iterator itr = std::lower_bound(container.begin(), container.end(), somevalue);
> if (itr > container.begin()) { ... }
>
> This compiled w/o problems, but since we use operator != in loops (as
> compared to <), I wondered whether using operator> is the Right Thing
> here, and if it would not be better to use
>
> if (itr != container.begin()) { ... }
>
> Opinions?
> R'

Only random access iterators can efficiently implement < and >.
(std::vector iterators are random access - in fact this will just be a
plain old pointer comparison)

If you switched to std::list you would have to recode so yes != would
be better because it is more general.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

 | 
Pages: 1
Prev: Code Optimization
Next: goto