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!

+3


source to share


6 answers


Not. If it is const

, it cannot be changed. You need to make a copy or grab it using a non-const link.



+6


source


You cannot put elements in a const vector, the state of the vectors is the elements it stores, and adding elements to the vector changes that state.

If you want to add to a vector, you must take a non-const ref.



void f(std::vector<int>& v)
{ 
    v.push_back(4);
}

      

+3


source


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.

+2


source


The whole point of the const vector is that you cannot change it. Adding an element to it would be a modification and therefore a violation of its constant. This is why you cannot do this. This is by design.

+1


source


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);
}

      

+1


source


you must remove const in your declaration or if it is not possible to use

const_cast<std::vector<std::string>& >(gradeReported).push_back(firstEntry);

      

-1


source







All Articles