Change 'class' to 'typename' in dependent contexts so the code compiles with VC++, g++, and clang++. I'm not sure why g++ works with 'class' in these contexts, but 'typename' is what is used by the standard.
Naked new's not being captured in some form of smart pointer is considered very bad form because so often, as is the case here, it is a sign of exception unsafe code. Doing unnecessary dynamic allocation is also considered a bad habit, as it is much less efficient and harder to debug than automatic allocation.

The usual recommendation from Stroustrup and other teachers of the language is to create temporary variables just before they are used.

Applying those rules results in a program that happens to workaround the iterator lifetime problem!
Re-factor by turning the two separate code blocks into separate functions. While this isn't strictly necessary, it demonstrates the preferred C++ practice of making each separable activity a separate function. In the long run, this improves the maintainability of the code.