C++ unordered_set XXX in read-only object

本文探讨了如何在C++中使用unordered_set来存储包含计数信息的元素,并解决了一个关键问题:如何更新这些元素的计数字段而不违反unordered_set的规则。通过将计数字段标记为mutable或者使用unordered_map作为替代方案,文章提供了实用的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

还是使用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。

参考

https://stackoverflow.com/questions/16452378/how-to-make-an-iterator-to-a-read-only-object-writable-in-c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值