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

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

    You can't create a vector of const ints, and it'd be pretty useless even if you could. If i remove the second int, then everything from there on is shifted down one -- read: modified -- making it impossible to guarantee that v[5] has the same value on two different occasions.

    Add to that, a const can't be assigned to after it's declared, short of casting away the constness. And if you wanna do that, why are you using const in the first place?

    0 讨论(0)
  • 2020-12-01 05:42

    You could derive a class const_vector from std::vector that overloads any method that returns a reference, and make it return a const reference instead. To do your sort, downcast back to std::vector.

    0 讨论(0)
提交回复
热议问题