why is c++ std::max_element so slow?

Before voting on this answer, please test (and verify) this on your machine and comment/add the results. Note that I used a vector size of 1000*1000*1000 for my tests. Currently, this answer has 19 upvotes but only one posted results, and these results did not show the effect described below (though obtained with a different … Read more

Reverse iterator returns garbage when optimized

Looking at std::reverse_iterator‘s libstdc++ implementation reveals something interesting: /** * @return A reference to the value at @c –current * * This requires that @c –current is dereferenceable. * * @warning This implementation requires that for an iterator of the * underlying iterator type, @c x, a reference obtained by * @c *x remains valid … Read more

Does std::vector::swap invalidate iterators?

The behavior of swap has been clarified considerably in C++11, in large part to permit the Standard Library algorithms to use argument dependent lookup (ADL) to find swap functions for user-defined types. C++11 adds a swappable concept (C++11 ยง17.6.3.2[swappable.requirements]) to make this legal (and required). The text in the C++11 language standard that addresses your … Read more

How can I add new methods to Iterator?

In your particular case, it’s because you have implemented your trait for an iterator of String, but your vector is providing an iterator of &str. Here’s a more generic version: use std::collections::HashSet; use std::hash::Hash; struct Unique<I> where I: Iterator, { seen: HashSet<I::Item>, underlying: I, } impl<I> Iterator for Unique<I> where I: Iterator, I::Item: Hash + … Read more

What is iterator invalidation?

Iterators are glorified pointers. Iterator invalidation is a lot like pointer invalidation; it means it suddenly points to junk data. Because it’s very natural but wrong to do things like this: for(iterator it = map.begin(); it != map.end(); ++it) { map.erase(it->first); // whoops, now map has been restructured and iterator // still thinks itself is … Read more