Search code examples
c++vectorcastingtype-conversionconst-cast

Can we convert a const vector<string> to vector<string> using const_cast?


Please forgive me if it is very basic. I like to use const_cast for the conversion. If it is possible can anyone please share the example. Other way which I'm avoiding is to iterate const vector and insert its content into a new vector.


Solution

  • const_cast doesn't introduce undefined behaviour (i.e., it's safe to use), as long as the variable you're const_casting wasn't originally defined as const or if it was originally defined as const you're not modifying it.

    If the above restrictions are kept in mind then you can do it for example in the following way:

    void foo(std::vector<std::string> const &cv) {
      auto &v = const_cast<std::vector<std::string>&>(cv);
      // ...
    }
    

    Live Demo