mike
mike

Reputation: 139

Getting strange error while trying to set up an iterator

This is probably a silly error but I can't seem to find what I have done wrong.

The error I am getting is no operator "=" matches these operands.

Here is my code...

void print_words(const map < string, int >& m1) {
map<string, int>::iterator it;
cout << "Number of non-empty words: " << m1.size() << '\n';

int count = 0;
for (it = m1.begin(); it != m1.end(); it++) {

    }
}

I get the error in the for loop in the it = m1.begin() statement and I cannot go on to print out the map if I can't iterate through it.

Upvotes: 1

Views: 37

Answers (2)

user835611
user835611

Reputation: 2376

Use a const_iterator or auto.

void print_words(const map < string, int >& m1) {
    cout << "Number of non-empty words: " << m1.size() << '\n';
    int count = 0;
    for (auto it = m1.cbegin(); it != m1.cend(); it++) {
    }
}

Upvotes: 0

Use a const iterator:

void print_words(const map < string, int >& m1) {
    cout << "Number of non-empty words: " << m1.size() << '\n';
    int count = 0;
    for (map<string, int>::const_iterator it = m1.cbegin(); it != m1.cend(); it++) {

    }
}

Upvotes: 1

Related Questions