Often, you have a map like map<string,X>
where the key is the name of the mapped value, and you need an API which lets consumers see all the names... to populate a GUI list-box for example.
You can build a vector and return it as an API call but this is rather inefficient. You could just return a reference to the map, but then the values are also accessible and you might not want that.
So how could you write a compliant class, KeyIterator, which wraps map and provides standard iterator access to the keys in that map.
e.g:
map<string,X> m= ...
KeyIterator<string> ki(m);
for(KeyIterator<string>::iterator it=ki.begin();it!=ki.end();++it)
cout << *it;
KeyIterator should be lightweight so you can return it from a method with virtually no overhead.
edit: I'm not sure I explained perfectly, let me give a better use-case (semi-pseudo):
class PersonManager
{
private:
map<string,Person> people;
public:
//this version has to iterate the map, build a new structure and return a copy
vector<string> getNamesStandard();
//this version returns a lightweight container which can be iterated
//and directly wraps the map, allowing access to the keys
KeyIterator<string> getNames();
};
void PrintNames(PersonManager &pm)
{
KeyIterator<string> names = pm.getNames();
for(KeyIterator<string>::iterator it=names.begin();it!=names.end();++it)
cout << *it << endl;
}