2

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?

4
  • 5
    std::vector<double>::iterator -> std::vector<double>::const_iterator. Commented Dec 28, 2019 at 0:32
  • 4
    Since C++11 it's easier to write the loop as either for (auto it = ds.begin(); it != ds.end(); it++) or for (double d : ds) { dum = dum + std::to_string(d) + " "; } Commented Dec 28, 2019 at 0:36
  • An iterator can be used to change the element of a vector, so cannot be used on a const vector. Use const_iterator instead. Commented Dec 28, 2019 at 0:41
  • Thanks. I prefer not to use auto, so as to improve my understanding. I thought of this basic issue. Note that I do not attempt to change the variable, so I thought the compiler would be OK with the code. I guess once one defines a regular iterator referencing a const variable, the compiler could lose track of what happens, and the variable could be changed, even if the code as written does not change it. so the compiler prevents that. For example, I could have passed the non-const iterator to a function in another source file, this could wreak havoc, etc. Commented Dec 28, 2019 at 0:51

1 Answer 1

5

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) + " "; 
Sign up to request clarification or add additional context in comments.

1 Comment

If your problem has been solved, don't forget to up-vote and select this as accepted answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.