How to navigate through a vector using iterators? (C++)

You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively. using namespace std; vector<string> myvector; // a vector of stings. // push some strings in the vector. myvector.push_back(“a”); myvector.push_back(“b”); myvector.push_back(“c”); myvector.push_back(“d”); vector<string>::iterator it; // declare an iterator … Read more

Iterate an iterator by chunks (of n) in Python?

The grouper() recipe from the itertools documentation’s recipes comes close to what you want: def grouper(n, iterable, fillvalue=None): “grouper(3, ‘ABCDEFG’, ‘x’) –> ABC DEF Gxx” args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) It will fill up the last chunk with a fill value, though. A less general solution that only works on sequences but … Read more

Difference between Java Enumeration and Iterator

Looking at the Java API Specification for the Iterator interface, there is an explanation of the differences between Enumeration: Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. The bottom line is, both Enumeration and … Read more

Iterate over the lines of a string

Here are three possibilities: foo = “”” this is a multi-line string. “”” def f1(foo=foo): return iter(foo.splitlines()) def f2(foo=foo): retval=”” for char in foo: retval += char if not char == ‘\n’ else ” if char == ‘\n’: yield retval retval=”” if retval: yield retval def f3(foo=foo): prevnl = -1 while True: nextnl = foo.find(‘\n’, … Read more

What happens if you call erase() on a map element while iterating from begin to end?

C++11 This has been fixed in C++11 (or erase has been improved/made consistent across all container types). The erase method now returns the next iterator. auto pm_it = port_map.begin(); while(pm_it != port_map.end()) { if (pm_it->second == delete_this_id) { pm_it = port_map.erase(pm_it); } else { ++pm_it; } } C++03 Erasing elements in a map does not … Read more