in reply to Re^4: foreach to for (related to my last question)
in thread foreach to for (related to my last question)

tricolaire:

OK, then, when you translate it to C++, make your life simpler and use STL. Then you'll find that your hashes, vectors and foreach loops translate fairly easily:

vector<X> aas; vector<X>::iterator aa; map<K,V> SEQ; map<K,V>::iterator seq; vector<Z> codons; vector<Z>::iterator codon; for (aa=aas.begin(); aa!=aas.end(); ++aa) { for (seq=SEQ.begin(); seq!=SEQ.end(); ++seq) { for (codon=codons.begin(); codon!=codons.end(); ++codon) { ... do something ... } } }
Also, what I've shown isn't great STL. There are functors and predicates that let you do things like map and grep. Give it a try. You'll find that it makes C++ much nicer. (Though it does take a bit of time to wrap your head around it when you start.)

--roboticus

Replies are listed 'Best First'.
Re^6: foreach to for (related to my last question)
by ikegami (Patriarch) on Jun 23, 2006 at 00:01 UTC
    Are you sure it's safe to add and delete items from a map while iterating over it? I personally don't know, so I'm just raising the issue.
      ikegami:

      Good question. I'll have to check...

      Update: It appears that you're correct--it seems that deleting a map element via the iterator would potentially shuffle the map enough that the iterator would be invalid. So to do the STL conversion, we'd need a bit of an algorithm change. (Like make a stack of iterators and push the ones you want to delete on the stack, and when the loop is done, pop off the items in the stack, deleting the things they point to.

      Yecch. Probably a better way out there. But I don't know it...

      Update 2: I've done some more digging. Deleting the element invalidates the iterator doing the pointing, but doesn't invalidate other iterators. So we could use a pair of iterators, one to scan and one to delete. A bit tricky looking, so I'll leave it as an exercise to the reader.... 8^)

      I hope this is a permanent link!

      Update 3 (and last!): I found a link in a mailing list that gives this handy list:

      vector -- all vector iterators are invalidated on any change
      string & wstring -- all string iterators are invalidated on any change
      deque -- all deque iterators are invalidated on any change, except for beginning and end removals
      list -- no list iterators are invalidated, except for those referring to a deleted element
      set & multiset -- no iterators are invalidated except ones pointing to a removed element
      map & multimap -- no iterators are invalidated except ones pointed to a removed element

      --roboticus