Returning an iterator is easy. For example, you can return the first iterator to vector types:
std::vector<std::string> types; // some code here std::vector<std::string>::iterator Union::returnTheBeginIterator() { return types.begin(); }
Java vs C ++
But C ++ iterators are not Java iterators: they are not used the same way.
In Java (IIRC) you are more like an enumerator, that is, you use the "next" method to iterate from one element to another. Thus, repeating from beginning to end is enough to return the Java iterator.
In C ++, an iterator is designed to behave like a super-pointer. Thus, it usually "points" to a value, and using the ++ operator, - etc. (Depending on the exact type of iterator), you can move the iterator to a "point" to the next, previous, etc. .. in the container.
Let iteration!
Usually you want to iterate from start to finish.
This, you need to return either the entire collection (like "const" if you want it to be read-only), and let the user iterate over the way he / she wants.
Or you can return two iterators, one for the beginning and one for the end. So you could:
std::vector<std::string>::iterator Union::typesBegin() { return types.begin(); } std::vector<std::string>::iterator Union::typesEnd() { return types.end(); }
And you can iterate from start to finish, in C ++ 03:
// alias, because the full declaration is too long typedef std::vector<std::string> VecStr ; void foo(Union & p_union) { VecStr::iterator it = p_union.typesBegin() ; VecStr::iterator itEnd = p_union.typesEnd() ; for(; it != itEnd; ++it) { // here, "*it" is the current string item std::cout << "The current value is " << *it << ".\n" ; } }
C ++ Version 11
If you provide a full container instead of your iterators, in C ++ 11, this becomes easier as you can use the range-for loop (like foreach in Java and C #):
void foo(std::vector<std::string> & p_types) { for(std::string & item : p_types) {
PS: Johannes Schaub - litb fairly uses the const qualifier whenever possible. I did not do this because I wanted to avoid code erosion, but, in the end, "const" is your friend.