Hey guys I am trying to print the contents of a map container I have. I seem to be getting a nasty error from the compiler which seems to come from the pos = wordList.begin() part. any suggestions?

map<string, unsigned>::iterator pos;
     for(pos = wordList.begin(); pos != wordList.end(); ++pos)
         {
         cout << "Key: " << pos->first << endl;
         cout << "Value:" << pos->second << endl;
         }

some of the error:
error: no match for âoperator=â in âpos =

I assume it's talking about the assignment of pos=wordlist.begin() . If so you'd imagine that wordlist isn't of type map<string,unsigned> from what the error says.

Can you post more code so we can see more of what you're doing?

Edited 7 Years Ago by twomers: n/a

#include <iostream>
#include <map>
#include <sstream>
#include <fstream>
#include <cstring>

using namespace std;

unsigned int read_words(map <string, unsigned>&);
string remove_punctuation(const string&);
void print_words(const map <string, unsigned>&, unsigned int);

int main()
        {
        map<string, unsigned> wordList;

	unsigned int numwords;
	
	numwords = read_words(wordList);
	
	print_words(wordList, numwords);

    system ("pause");
	return 0;
	}

unsigned int read_words(map <string, unsigned>& wordList)
	{
    ifstream inFile;
	inFile.open("data5.txt");

	if(inFile.fail())
		{
		cout << "input file did not open";
		exit(0);
		}

	string word;
	string newWord;
	unsigned int numCount = 0;

	while(inFile >> word)
	{
	newWord = remove_punctuation(word);
	if(newWord.length() > 0)
		{
		wordList[newWord]++;
		numCount++;
	    }
    }
	return numCount;
	}

string remove_punctuation(const string& word)
       {       
       word.c_str();
       string fixWord;
       fixWord.c_str();
       int fixCount = 0;
       string temp;
       
       for(int i = 0; word[i] != NULL; ++i)
               {
               if(isalpha(word[i]))
               {
               fixWord[fixCount] = tolower(word[i]);
               ++fixCount;
               }
               }
       temp = fixWord;
       return temp;
       }

void print_words(const map <string, unsigned>& wordList, unsigned int numwords)
     {
     cout << numwords;
     
     map<string, unsigned>::iterator pos;
     for(pos = wordList.begin(); pos != wordList.end(); ++pos)
	 {
	 cout << "Key: " << pos->first << endl;
	 //cout << "Value:" << pos->second << endl;
	 }
     }

You're passing in a const map, so you've gotta use a const_iterator: map<string,unsigned>::const_iterator pos; should work.

To explain. A const_iterator doesn't allow you modify anything in the map, while you may with iterator s.

Edited 7 Years Ago by twomers: n/a

This article has been dead for over six months. Start a new discussion instead.