How can I improve this design that forces me to declare a member function const and declare variables mutable?

前端 未结 3 1144
情深已故
情深已故 2020-12-20 20:26

For some reason I am iterating over elements of a class in an std::set and would like to slightly modify the keys, knowing that the order will be unchanged.

3条回答
  •  长情又很酷
    2020-12-20 20:59

    You can't. Set elements are required to be const for container correctness:

    It forces you to realize that the key part needs to be immutable, or the data structure invariants would be broken.

    struct element 
    {
         std::string key_part; // const in the set
    
         bool operator<(const element&o) const { return key_part

    If you wanted to retain the possibility to 'express' const-ness in the non-key part, split it out into pairs and store them in a map:

    std::map mapped;
    

    or, more flexibly:

    struct element 
    {
         std::string key_part; // const in the set
    
         bool operator<(const element&o) const { return key_part mapped;
    

提交回复
热议问题