Convert Iterator to List

Better use a library like Guava: import com.google.common.collect.Lists; Iterator<Element> myIterator = … //some iterator List<Element> myList = Lists.newArrayList(myIterator); Another Guava example: ImmutableList.copyOf(myIterator); or Apache Commons Collections: import org.apache.commons.collections.IteratorUtils; Iterator<Element> myIterator = …//some iterator List<Element> myList = IteratorUtils.toList(myIterator);

How to correctly implement custom iterators and const_iterators?

Choose type of iterator which fits your container: input, output, forward etc. Use base iterator classes from standard library. For example, std::iterator with random_access_iterator_tag.These base classes define all type definitions required by STL and do other work. To avoid code duplication iterator class should be a template class and be parametrized by “value type”, “pointer … Read more

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

http://www.cplusplus.com/reference/std/iterator/ has a handy chart that details the specs of ยง 24.2.2 of the C++11 standard. Basically, the iterators have tags that describe the valid operations, and the tags have a hierarchy. Below is purely symbolic, these classes don’t actually exist as such. iterator { iterator(const iterator&); ~iterator(); iterator& operator=(const iterator&); iterator& operator++(); //prefix increment … Read more

Sorting a vector in descending order

Actually, the first one is a bad idea. Use either the second one, or this: struct greater { template<class T> bool operator()(T const &a, T const &b) const { return a > b; } }; std::sort(numbers.begin(), numbers.end(), greater()); That way your code won’t silently break when someone decides numbers should hold long or long long … Read more

C++ Loop through Map

You can achieve this like following : map<string, int>::iterator it; for (it = symbolTable.begin(); it != symbolTable.end(); it++) { std::cout << it->first // string (key) << ‘:’ << it->second // string’s value << std::endl; } With C++11 ( and onwards ), for (auto const& x : symbolTable) { std::cout << x.first // string (key) << … Read more