List iterator + operator

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

So, I have the worst code in the world here. Is there a better way to do this?

When using '+ 1', I get the following:

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

Why not split into multiple lines:

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

where iterator is the type of iterator for the list. Personally, I probably would have pulled ++nextEntry onto my line for more clarity - but this is probably a subjective solution.

+8
source share

What about the helper function:

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

Then you can replace (++currentEntry)-- with Next(currentEntry)

Edit: Or even better: if you use Boost, see Rob's suggestion next and previous in the Utility library

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

or

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

You can use reverse iterators, for example:

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

will add new elements to the end.

Of course, whether this will work for you depends on how you use your iterator.

0
source share

Since you do not want to influence your currentEntry iterator, and you want to insert an element after currentEntry, currentEntry + 1 is the best bet.

0
source share

All Articles