还是使用struct作为unordered_set的数据结构,假设我们有如下代码:
struct SentimentWord {
string word;
int count;
};
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;
}
int main()
{
//...
//...
unordered_set<SentimentWord, SentimentWordHash> positiveWords;
unordered_set<SentimentWord, SentimentWordHash>::iterator iter;
iter = positiveWords.find(temp);
if(iter != positiveWords.end()){
iter->count++;
}
}
理论上说,unordered_set中的key一旦插入是不可修改的:
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.
考虑到底层红黑树的结构,修改key将会改变整个红黑树的构造。不过,我们已经将unordered_set
的hasher设置为用户自定义,并且只使用其中的string成员作为hash函数的输入。
为了解决这个问题,可以做如下修改:
struct SentimentWord {
string word;
mutable int count;//使用mutable修饰
};
也可以使用unordered_map
把count作为value。