我不确定如何在不创建额外变量的情况下解决此问题。这是无法编译的代码:
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;
}
如果删除输入上的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;
}
我有理由想要const。什么是获得相同功能但不删除const的方法?
A const_iterator
是一个指向const值的迭代器(类似于const T *指针);取消引用它会返回对常量值(const T&)的引用,并防止修改引用的值:它强制执行const-correctness。
具有对容器的const引用时,只能获得const_iterator。
将迭代器更改为const_iterator:
std::vector<double>::const_iterator it;
或使用auto:
for (auto it = ds.begin(); it != ds.end(); it++) { // Compiler error. No suitable "="
dum = dum + std::to_string(*it) + " ";
}
for (auto a: ds)
dum = dum + std::to_string(a) + " ";