unordered_set non const iterator

后端 未结 5 1263
野趣味
野趣味 2021-01-04 23:39

For testing purposes I created a little unordered_set and tried to iterate over the set. The set holds an own class:

class Student {
private:
    int matrNr;
         


        
5条回答
  •  再見小時候
    2021-01-05 00:19

    Both set and unordered_set have read-only keys. It's easy to see why this is the case - if the key value were to change, the data structure would have it filed in the wrong spot and you wouldn't be able to find it anymore.

    Per your example, suppose your hash function simply returned the matrNr field. When the hash number changes, any lookup for 1234 will fail because there's nothing stored in that hash bucket.

    It could be possible to change some part of the object that is not used in making the hash key, but that would lead to possible hard to track down bugs. The standards committee decided to eliminate that possibility by making the entire key const.

    There are two ways around this restriction. The first is to split the key from the value and use a map or unordered_map instead. The second is to remove the item from the set and reinsert it after it's modified.

提交回复
热议问题