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

后端 未结 14 599
既然无缘
既然无缘 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:24

    If constness is important to you in this instance I think you probably want to work with immutable types all the way up. Conceptually you'll have a fixed size, const array of const ints. Any time you need to change it (e.g. to add or remove elements, or to sort) you'll need to make a copy of the array with the operation performed and use that instead. While this is very natural in a functional language it doesn't seem quite "right" in C++. getting efficient implementations of sort, for example, could be tricky - but you don't say what you're performance requirements are. Whether you consider this route as being worth it from a performance/ custom code perspective or not I believe it is the correct approach.

    After that holding the values by non-const pointer/ smart pointer is probably the best (but has its own overhead, of course).

提交回复
热议问题