Returning an iterator is easy. For example, you can return the first iterator in the 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 have more like an enumerator, that is, you use the method "next" to iterate from one item to the next. Thus, returning the Java iterator is enough to iterate from the begining to the end.
In C++, the iterator is designed to behave like a super-pointer. Thus, it usually "points" to the value, and using the operator ++, --, etc. (depending on the exact type of the iterator), you can move the iterator to "point" to the next, previous, etc. value in the container.
Let's iterate!
Usually, you want to iterate from the beginning to the end.
This, you need to return either the whole collection (as "const", if you want it to be readonly), and let the user iterate the way he/she wants.
Or you can return two iterators, one for the beginning, and one for the end. So you could have:
std::vector<std::string>::iterator Union::typesBegin()
{
return types.begin();
}
std::vector<std::string>::iterator Union::typesEnd()
{
return types.end();
}
And the, you can iterate from the beginning to the end, 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++11 version
If you provide the full container instead of only its iterators, in C++11, it becomes easier, as you can use the range-for loop (as the foreach in Java and C#):
void foo(std::vector<std::string> & p_types)
{
for(std::string & item : p_types)
{
// here, "item " is the current string item
std::cout << "The current value is " << item << ".\n" ;
}
}
P.S.: Johannes Schaub - litb is right in using the "const" qualifier whenever possible. I did not because I wanted to avoid to dilute the code, but in the end, "const" is your friend.