Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 916
Karn Avatar asked Sep 24 '26 17:09

Karn


2 Answers

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

like image 145
101010 Avatar answered Sep 26 '26 06:09

101010


Make a non-const copy of a vector given a const std::vector<X>& you can just write

void foo(const std::vector<std::string>& src) {
    std::vector<std::string> localcopy(src);
    ... localcopy can be modified ...
}

if however you only need to access a local read-write copy and not the original src the code can be simplified to

void foo(std::vector<std::string> localcopy) {
    ...
}

i.e. you just pass the vector by value instead of by reference: the vector that the caller is passing will not be modified by the callee because a copy will be made implicitly at call time.

like image 37
6502 Avatar answered Sep 26 '26 08:09

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!