How to implement an STL-style iterator and avoid common pitfalls?

I made a collection for which I want to provide an STL-style, random-access iterator. I was searching around for an example implementation of an iterator but I didn’t find any. I know about the need for const overloads of [] and * operators. What are the requirements for an iterator to be “STL-style” and what … Read more

How to avoid “ConcurrentModificationException” while removing elements from `ArrayList` while iterating it? [duplicate]

This question already has answers here: Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop (30 answers) Closed 7 years ago. I’m trying to remove some elements from an ArrayList while iterating it like this: for (String str : myArrayList) { if (someCondition) { myArrayList.remove(str); } } Of course, I get a … Read more

Get the first item from an iterable that matches a condition

I would like to get the first item from a list matching a condition. It’s important that the resulting method not process the entire list, which could be quite large. For example, the following function is adequate: def first(the_iterable, condition = lambda x: True): for i in the_iterable: if condition(i): return i This function could … Read more

What is the most effective way to get the index of an iterator of an std::vector?

I’m iterating over a vector and need the index the iterator is currently pointing at. AFAIK this can be done in two ways: it – vec.begin() std::distance(vec.begin(), it) What are the pros and cons of these methods? 10 s 10 I would prefer it – vec.begin() precisely for the opposite reason given by Naveen: so … Read more