Jookia
Jookia

Reputation: 6880

list iterator + operator

// ((++currentEntry)--) is equivalent to (currentEntry + 1). Kind of.
menuEntries.insert((++currentEntry)--, newEntries.begin(), newEntries.end());

So I have the world's worst piece of code here. Is there a better way to do this?

When using '+ 1' I get this:

source/menu.cpp:146:37: error: invalid operands to binary expression
      ('list<menuEntry *>::iterator' (aka '_List_iterator<menuEntry *>') and
      'int')
                            menuEntries.insert(currentEntry + 1, ...
                                               ~~~~~~~~~~~~ ^ ~

Upvotes: 4

Views: 1422

Answers (5)

&#201;ric Malenfant
&#201;ric Malenfant

Reputation: 14148

How about a helper function:

template<class IterT>
IterT Next(IterT i)
{
  return ++i;
}

You could then replace (++currentEntry)-- by Next(currentEntry)

Edit: Or even better: If you use Boost see Rob's suggestion of next and prior in the Utility library

Upvotes: 2

robev
robev

Reputation: 1949

Since you don't want to affect your currentEntry iterator, and you want to insert the member after currentEntry, currentEntry + 1 is the best bet.

Upvotes: 0

James
James

Reputation: 25533

You can use reverse iterators, for example:

myList.insert(myList.rbegin(), newEntries.begin(), newEntries.end())

would add the new items to the end.

Of course, whether this works for you depends on how you are using your iterator.

Upvotes: 0

winwaed
winwaed

Reputation: 7801

Why not split into multiple lines:

iterator nextEntry = currentEntry;
menuEntries.insert( ++nextEntry, newEntries.begin(), newEntries.end());

where iterator is iterator type for the list. Personally, I would probably pull the ++nextEntry onto its own line for further clarity - but that is probably a subjective decision.

Upvotes: 8

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133014

++currentEntry;
menuEntries.insert(currentEntry, newEntries.begin(), newEntries.end());
--currentEntry;

or

menuEntries.insert(++currentEntry, newEntries.begin(), newEntries.end());
--currentEntry;

Upvotes: 0

Related Questions