为什么 const 阻止编译?

Ant*_*cci 2 c++ constants

我不确定如何在不创建额外变量的情况下解决此问题。这是无法编译的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果我删除输入上的 const,它会编译:

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;
}
Run Code Online (Sandbox Code Playgroud)

我有理由想要常量。获得相同功能但不删除常量的方法是什么?

abh*_*ora 5

Aconst_iterator是指向 const 值的迭代器(如 const T* 指针);取消引用它返回对常量值(const T&)的引用并防止修改引用的值:它强制执行const-correctness

当您拥有对容器的 const 引用时,您只能获得一个 const_iterator。

将迭代器更改为 const_iterator:

std::vector<double>::const_iterator it;
Run Code Online (Sandbox Code Playgroud)

或使用自动

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

基于范围的 for 循环

for (auto a: ds)
    dum = dum + std::to_string(a) + " ";
Run Code Online (Sandbox Code Playgroud)