C++ deque: when iterators are invalidated

push_back() and push_front() are defined in terms of insert(). Similarly, pop_back() and pop_front() are defined in terms of erase(). Here’s what the C++03 standard says about iterator invalidation for insert() (23.2.1.3/1): An insert in the middle of the deque invalidates all the iterators and references to elements of the deque. An insert at either end … Read more

When should I use `drain` vs `into_iter`?

They are somewhat redundant with each other. However, as you say, Drain just borrows the vector, in particular, it has a lifetime connected with the vector. If one is wishing to return an iterator, or otherwise munge iterators in the most flexible way possible, using into_iter is better, since it’s not chained to the owner … Read more

How to create a copy of an iterator? [duplicate]

Use the itertools.tee() function to produce copies; these use a buffer to share results between different iterators: from itertools import tee my_list = [5, 4, 3,2] first_it = iter(my_list) first_it, second_it = tee(first_it) print next(first_it) # prints 5 print next(second_it) # prints 5 print next(first_it) # prints 4 Note that you should no longer use … Read more

How do you remove elements from a std::vector while iterating? [duplicate]

The erase() method returns a new (valid) iterator that points to the next element after the deleted one. You can use this iterator to continue with the loop: std::vector<std::string>::iterator iter; for (iter = m_vPaths.begin(); iter != m_vPaths.end(); ) { if (::DeleteFile(iter->c_str())) iter = m_vPaths.erase(iter); else ++iter; }

how the iterator in c++ could be printed?

Yes, there is a way to do it! You can’t print the iterator because it is not defined to have a value. But you can perform arithematic operations on them and that helps you to print the value (of the iterator). Do the following. cout << it – v.begin(); Example: #include <iostream> #include <algorithm> #include … Read more