如何使只读对象的迭代器可写(在 C++ 中)

use*_*561 1 c++ pointers iterator

我创建了一个unordered_set我自己类型的struct. 我有一个iterator该集合,并希望增加该集合count的成员 ( ) 所指向的。但是,编译器会抱怨以下消息:structiterator

\n\n

main.cpp:61:18: error: increment of member \xe2\x80\x98SentimentWord::count\xe2\x80\x99 in read-only object

\n\n

我怎样才能解决这个问题?

\n\n

这是我的代码:

\n\n
#include <fstream>\n#include <iostream>\n#include <cstdlib> \n#include <string>\n#include <unordered_set>\n\n\nusing namespace std;\n\n\nstruct SentimentWord {\n  string word;\n  int count;\n};\n\n\n//hash function and equality definition - needed to used unordered_set with type   SentimentWord\nstruct SentimentWordHash {\n  size_t operator () (const SentimentWord &sw) const;\n};\n\nbool operator == (SentimentWord const &lhs, SentimentWord const &rhs);\n\n\n\nint main(int argc, char **argv){\n\n\n  ifstream fin;\n  int totalWords = 0;\n  unordered_set<SentimentWord, SentimentWordHash> positiveWords;\n  unordered_set<SentimentWord, SentimentWordHash> negativeWords;\n\n\n  //needed for reading in sentiment words\n  string line;\n  SentimentWord temp;\n  temp.count = 0;\n\n\n  fin.open("positive_words.txt");\n  while(!fin.eof()){\n    getline(fin, line);\n    temp.word = line;\n    positiveWords.insert(temp);\n  }\n  fin.close();\n\n\n  //needed for reading in input file\n  unordered_set<SentimentWord, SentimentWordHash>::iterator iter;\n\n\n  fin.open("041.html");\n  while(!fin.eof()){\n    totalWords++;\n    fin >> line;\n    temp.word = line;\n    iter = positiveWords.find(temp);\n    if(iter != positiveWords.end()){\n      iter->count++;\n    }\n  }\n\n\n  for(iter = positiveWords.begin(); iter != positiveWords.end(); ++iter){\n    if(iter->count != 0){\n      cout << iter->word << endl;\n    }\n  }\n\n\n  return 0;\n\n}\n\n\nsize_t SentimentWordHash::operator () (const SentimentWord &sw) const {\n  return hash<string>()(sw.word);\n}\n\n\nbool operator == (SentimentWord const &lhs, SentimentWord const &rhs){\n  if(lhs.word.compare(rhs.word) == 0){\n    return true;\n  }\n  return false;\n} \n
Run Code Online (Sandbox Code Playgroud)\n\n

任何帮助是极大的赞赏!

\n

小智 5

根据定义, an 中的元素unordered_set是不可变的:

在 unordered_set 中,元素的值同时也是其唯一标识它的键。键是不可变的,因此,unordered_set 中的元素一旦进入容器就无法修改 - 但它们可以插入和删除。

我投票赞成您使用 unordered_map代替,使用字符串作为键,使用 int 作为映射值。