I didn't find any information about iterators. Can you explain? |
I daresay you did not really look well enough. I just ran "c++ iterator" on Google and found many interesting results. In any case, an iterator is the STL-equivalent to a pointer used to "travel along" an array. If you use a "pure C" array like char array[10] = "wow";you can loop on it by saying for(char* ptr = array; *ptr != '\0'; ptr++) { cout << *ptr; }If you use a generic STL container, like e.g. vector<>, you say vector More precisely, iterators are objects for which the unary operator * and the increment and decrement operators ++ and -- have been overloaded, so that they behave like pointers. An iterator does NOT contain, like a pointer does, simply a memory address. But an iterator will contain some private data which allows it to behave like a pointer (i.e. one of its fields contains a memory address). The overloaded unary operator * will return the object pointed to by the private data contained within the iterator, and the overloaded ++ (respectively --) operator will change the private data within the iterator so that the iterator "points" to the next (respectively previous) element in the STL container. One important caveat: whereas pointers obey a linear ordering, iterators do not necessarily do so. In other words, if two pointers char* p1; char* p2;are such that p1 < p2, then you may be sure that by repeatedly issuing the statement p1++;you will eventually make the condition p1 == p2true. This is not necessarily true of iterators (at least not in all STL releases or implementations). The upshot of this is: the loop for(vector(where the important issue is that the termination conditions is vi < myVector.end() instead of vi != myVector.end()) may never terminate! |
How can I transform an STL std::string to a pointer of char, i.e. char *? |
string myString = "wow"; char* myArray = myString.c_str();Do NOT delete myArray, its allocation and deallocation is handled directly by the string class. |