Anthony Mannucci
Anthony Mannucci

Reputation: 287

Why does const prevent this from compiling?

I am not sure how to fix this problem without creating an extra variable. Here is the code that does not compile:

std::string & printVec(std::vector<double> const &ds, std::string &dum) {
    std::vector<double>::iterator it;
//    std::vector<double> dsi = ds; // Created just to get the code to work, using dsi.begin() etc. 
    dum = " ";
    for (it = ds.begin(); it != ds.end(); it++) { // Compiler error. No suitable "="
        dum = dum + std::to_string(*it) + " ";
    }
    return dum;
}

If I remove the const on the input, it compiles:

std::string & printVec(std::vector<double> &ds, std::string &dum) {
    std::vector<double>::iterator it;
    dum = " ";
    for (it = ds.begin(); it != ds.end(); it++) {
        dum = dum + std::to_string(*it) + " ";
    }
    return dum;
}

I have reasons to want the const. What is a way to get the same functionality but not remove the const?

Upvotes: 2

Views: 159

Answers (1)

abhiarora
abhiarora

Reputation: 10430

A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value (const T&) and prevents modification of the referenced value: it enforces const-correctness.

When you have a const reference to the container, you can only get a const_iterator.

Change the iterator to const_iterator:

std::vector<double>::const_iterator it;

or use auto:

for (auto it = ds.begin(); it != ds.end(); it++) { // Compiler error. No suitable "="
    dum = dum + std::to_string(*it) + " ";
}

or range based for loop:

for (auto a: ds)
    dum = dum + std::to_string(a) + " ";

Upvotes: 5

Related Questions