gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:02 24 4
gpt4 key购买 nike

我已经创建了一个属于我自己类型的 structunordered_set。我有一个 iterator 到这个集合,我想增加 struct 的一个成员(count),iterator 指向。但是,编译器会提示以下消息:

main.cpp:61:18: 错误:只读对象中成员“SentimentWord::count”的增量

我该如何解决这个问题?

这是我的代码:

#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;
}

非常感谢任何帮助!

最佳答案

unordered_set 中的元素是 by definition , 不可变的:

In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely. Keys are immutable, therefore, the elements in an unordered_set cannot be modified once in the container - they can be inserted and removed, though.

我会投票给你使用 unordered_map相反,使用字符串作为键,使用 int 作为映射值。

关于c++ - 如何使只读对象的迭代器可写(在 C++ 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16452378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com