Brandon Thompson
Brandon Thompson

Reputation: 125

Incrementing an Iterator with and without creating a template

I'm writing a very simple line of code to display the contents of a map container and I came across an interesting error. If I write:

    void DisplayMap(const map<int, string>&  myMap)
{
    for (const map<int, string>::const_iterator myIterator = myMap.begin(); 
         myIterator != myMap.end(); ++myIterator)
    {
        cout << myIterator->first << ": " << myIterator->second << endl;
    }   
}

The compiler has objection to my use of ++myIterator, claiming this function has no overloaded operator of type '++'. But, if I make this a Template:

template <typename T>
void DisplayMap(const T&  myMap)
{
    for (map<int, string>::const_iterator myIterator = myMap.begin(); myIterator != myMap.end(); ++myIterator)
    {
        cout << myIterator->first << ": " << myIterator->second << endl;    
    }
}

Then there is no issue. The code runs perfectly. I was hoping someone could explain why the compiler has no issue here. As I understand it, making the function a template is akin to invoking auto for a variable type. But what exactly is the compiler doing?

Thanks for your time.

Upvotes: 0

Views: 51

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

Most of the iterator and template stuff is not that relevant here. What is relevant is the const:

    for (const map<int, string>::const_iterator myIterator = myMap.begin(); 
               myIterator != myMap.end(); ++myIterator)
          ^^ !!!

You cannot increment a const iterator because it is const. You would get similar error for

for (const int i= 0; i< N; ++i) {

Here, i cannot be incremented because it is const.

In your template version you dropped the const, thats why there is no error.

Upvotes: 5

Related Questions