I am having trouble trying to write a function that takes in an object, and iterates through the list within that object, to print out the list. It is a dictionary type assignment, so it should print out a list of words. I cannot figure out how to access the list.
#include "Lexicon.h"
#include <iostream>
#include <list>
usingnamespace std;
// Default constructor for empty lexicon
Lexicon::Lexicon() {
lexicon = list<string>();
}
// Constructor that takes in words from file, and stores them in a lexicon.
// If file does not exist, exception is thrown.
Lexicon::Lexicon(const string& fileName) {
lexicon = list<string>();
}
// Returns true if word is in dictionary, false otherwise
bool Lexicon::containsWord(const string& word) {
for(list<string>::iterator it = lexicon.begin(); it != lexicon.end(); it++) {
if (*it == word) {
returntrue;
}
}
returnfalse;
}
// Adds word to lexicon if it is not already there
void Lexicon::addWord(const string& str) {
for(list<string>::iterator it = lexicon.begin(); it != lexicon.end(); it++) {
if (*it == str) {
return;
}
}
lexicon.push_back(str);
}
ostream& operator<<(ostream& os, const Lexicon& l) {
for (list<string>::iterator it = l.lexicon.begin(); it != l.lexicon.end(); it++) {
os << *it << endl;
}
return os;
}
edit: The rest of the program is not complete, I have been focusing on this so far, so I am aware there are probably issues there as well.
(the overloaded << operator is what is troubling me).
JLBorges, that first bit about the const_iterator makes sense, thank you. It was not explained very well in class, so I am having troubling understanding some of the list functionalities.
However, changing that still does not let me iterate, I am getting an error on
1 2 3
for (list<string>const_iterator it = l.lexicon.begin(); it != l.lexicon.end(); it++ ) {
os << *it << endl;
}
[Error] conversion from 'std::list<std::basic_string<char> >::const_iterator {aka std::_List_const_iterator<std::basic_string<char> >}' to non-scalar type 'std::list<std::basic_string<char> >::iterator {aka std::_List_iterator<std::basic_string<char> >}' requested