Re: How to write previous element in STL list
On Jul 27, 6:16 pm, cornelis van der bent
<kees.van.der.b...@gmail.com> wrote:
On 27 jul, 17:42, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
cornelis van der bent wrote:
In my code I want to go through all combinations of two
items in a list. Here is my code:
list<Instance*>::iterator i;
for (i = instances.begin(); i != --instances.end(); i++)
{
list<Instance*>::iterator j;
for (j = i + 1; j < instances.end(); j++)
{
// Do something!
}
}
I get a big error message at i + 1.
Such an operation is only defined for random-access
iterators, and the list iterator isn't one.
Do you know reason(s) why this has nog been implemented for a
list? The list is doubly-linked, so giving back an iterator
one postion earlier/further does not seem to be a big deal.
But operator+ isn't limited to adding one. Operator+ is defined
when it can be done in constant time; with list, it requires
linear time (with regards to what is being added).
One simple solution would be to define functions succ and prec:
template< typename ForwardIterator >
ForwardIterator
succ( ForwardIterator i )
{
++ i ;
return i ;
}
template< typename BidirectionalIterator >
BidirectionalIterator
prec( BidirectionalIterator i )
{
-- i ;
return i ;
}
More generally, one does wonder why std::advance takes a
reference to the iterator and updates it, rather than taking an
iterator, and returning the modified iterator.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34