Aside from the general rule about iterators that others have explained, in the case of the code you put up there, the iterator is a stack variable whose scope is local to the block where it's declared (and that is almost always how you declare iterators) , so deleting it wouldn't make any more sense than deleting any other stack variable that gets cleaned up when it goes out of scope. You only calldelete
on something you allocated withnew
.
Also somewhat relevant here: You wrote vector<int>* v = new vector<int>()
, which means v is a pointer and allocated on the "heap" (free-store) so you need to delete it explicitly. But in your example you only usedv
locally, so you have no reason to use a pointer at all and you shouldn't be using one. Just write std::vector<int> v;
and use it directly: it = v.begin()
, as @keyser explained, and just as you're actually doing with the iterator. When you do so, you no longer call delete v;
v
will get cleaned up automatically when it goes out of scope, just likeit
is cleaned up now.
Maybe you need to read up a bit on RAII, one of the fundamentals of good C++ programming. If you're coming from a Java or Delphi or C# background, it is a novel concept because in those languages all you get are references to objects on the heap (or where-ever the compiler and run-time decide to put them) but that's not the case in C++. You should learn to take advantage of this feature as much as possible in your C++ code. In C++, pointers to objects should be the exception, not the rule.