Chameleon said:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.
My question is this:
Can you tell me one case which an iterator is better than index?
For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.
I think, for using vector & map, index is far more useful than iterator
ignoring container types that do not support random access (list, set,
etc.), iterators still offer:
- pointer like semantics (think of string::iterator vs char*)
- generalized concept usable beyond iteration over elements inside a
container
- semi-container-independend way to access elements (whatever scott
meyers tells you otherwise

- better performance than container member functions in a few cases
- etc.
whenever you would like to utilize one of the above you might think
about using iterators instead of member functions.
try to implement the following examples without iterators:
// convert string to upper case
std::string s("hello world");
std::transform(s.begin(), s.end(), s.begin(), toupper);
// reverse any map
template <typename MapT>
std::multimap<typename MapT::mapped_type, typename MapT::key_type>
reverse(const MapT& input)
{
std::multimap<typename MapT::mapped_type, typename MapT::key_type>
result;
for(typename MapT::const_iterator I = input.begin();
I != input.end(); ++I)
result.insert(std::make_pair(I->second, I->first));
return result;
}
// print any container
// where ostream operator<< is defined for container::value_type
template <typename ContainerT>
void
print(const ContainerT& input, const std::string& separator=" ")
{
std::copy(input.begin(), input.end(),
std:

stream_iterator<typename ContainerT::value_type>
(std::cout, separator.c_str()));
}
-- peter