How do I put elements into a const vector?
I've tried a bunch of different ways, but I can't figure it out. The ad that was given to me is as follows:
const std::vector<std::string>&,
I tried to do this:
gradeReported.push_back(firstEntry);
I am getting an error. I'm pretty sure it has something to do with the const character of the vector. Help would be appreciated!
source to share
If you have a vector const
, this means that you can only read elements from that vector.
The same rules apply to a vector relative to any other type when you use a qualifier const
.
To be able to modify it, you either have to make a copy of the original vector, or take a non-contact link.
source to share
You shouldn't be able to change it, such a point in const. It is mainly used to pass parameters to functions / methods and with confidence that it will not be changed.
If you really need to change it, there are two options:
- Make a copy of the vector and modify it.
- Remove const via const_cast.
Making a copy
const std::vector<std::string>& foo;
std::vector<std::string> bar(foo);
Removing const via const_cast
I would highly recommend not using this, but it might be an option.
Assuming that the string vector is const-protected before being passed as a parameter to a method or function, and that the base type is not const
, in fact, we can do the following:
typedef std::vector<std::string> string_vector;
void f(const string_vector& foo) {
const string_vector& foo;
const_cast<string_vector>(foo).push(firstEntry);
}
int main() {
string_vector foo();
f(foo);
}
source to share