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.
Asked
Active
Viewed 2,103 times
3
-
3If you don't want to modify the original then why do you need the `const_cast`? – Galik Jan 25 '16 at 07:27
2 Answers
3
const_cast
doesn't introduce undefined behaviour (i.e., it's safe to use), as long as the variable you're const_cast
ing 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);
// ...
}

101010
- 41,839
- 11
- 94
- 168
3
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.

6502
- 112,025
- 15
- 165
- 265
-
Thanks. It is helpful. Is there any way we can remove the const flag from src(way we do using const_cast)? so that we can use the same src variable as a non cost vector. I'm just thinking if there is a way to avoid a copy in localcopy variable and use the same src variable? – Karn Jan 25 '16 at 08:53