Can I use const in vectors to allow adding elements, but not modifications to the already added?

后端 未结 14 636
既然无缘
既然无缘 2020-12-01 04:54

My comments on this answer got me thinking about the issues of constness and sorting. I played around a bit and reduced my issues to the fact that this code:



        
14条回答
  •  半阙折子戏
    2020-12-01 05:29

    I've been thinking a bit on this issue and it seems that you requirement is off.

    You don't want to add immutable values to your vector:

    std::vector vec = /**/;
    std::vector::const_iterator first = vec.begin();
    
    std::sort(vec.begin(), vec.end());
    
    assert(*vec.begin() == *first); // false, even though `const int`
    

    What you really want is your vector to hold a constant collection of values, in a modifiable order, which cannot be expressed by the std::vector syntax even if it worked.

    I am afraid that it's an extremely specified task that would require a dedicated class.

提交回复
热议问题