我創建了自己的struct
類型的unordered_set
。我有一個iterator
這個集合,並且想要增加iterator
指向的struct
的成員(count
)。然而,編譯器會抱怨以下消息:如何使只讀對象的迭代器可寫(使用C++)
main.cpp:61:18: error: increment of member ‘SentimentWord::count’ in read-only object
我該如何解決這個問題?
這裏是我的代碼:
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include <unordered_set>
using namespace std;
struct SentimentWord {
string word;
int count;
};
//hash function and equality definition - needed to used unordered_set with type SentimentWord
struct SentimentWordHash {
size_t operator() (const SentimentWord &sw) const;
};
bool operator == (SentimentWord const &lhs, SentimentWord const &rhs);
int main(int argc, char **argv){
ifstream fin;
int totalWords = 0;
unordered_set<SentimentWord, SentimentWordHash> positiveWords;
unordered_set<SentimentWord, SentimentWordHash> negativeWords;
//needed for reading in sentiment words
string line;
SentimentWord temp;
temp.count = 0;
fin.open("positive_words.txt");
while(!fin.eof()){
getline(fin, line);
temp.word = line;
positiveWords.insert(temp);
}
fin.close();
//needed for reading in input file
unordered_set<SentimentWord, SentimentWordHash>::iterator iter;
fin.open("041.html");
while(!fin.eof()){
totalWords++;
fin >> line;
temp.word = line;
iter = positiveWords.find(temp);
if(iter != positiveWords.end()){
iter->count++;
}
}
for(iter = positiveWords.begin(); iter != positiveWords.end(); ++iter){
if(iter->count != 0){
cout << iter->word << endl;
}
}
return 0;
}
size_t SentimentWordHash::operator() (const SentimentWord &sw) const {
return hash<string>()(sw.word);
}
bool operator == (SentimentWord const &lhs, SentimentWord const &rhs){
if(lhs.word.compare(rhs.word) == 0){
return true;
}
return false;
}
任何幫助,不勝感激!
[你可以通過不使用std :: set來解決這個問題](ftp://24.151.202.80/AiDisk_a1/Full/Completed/pdf/col1.pdf) – 2013-05-09 00:29:15
[另一個帶'eof' bug的代碼?](http://stackoverflow.com/questions/2251433/checking-for-eof-in-stringgetline)(在while-condition中使用getline代替...) – leemes 2013-05-09 00:59:43