Bre*_*men 1 c++ iterator stl vector
我不能在下面的代码中使用=运算符,因为我得到compiller错误.我无法理解有什么不对.
int CProcessData::calculateMidPoints(const std::vector<double>& xv, const std::vector<double>& yv)
{
if((0 == xv.size()) || (0 == yv.size()))
return 1;
std::vector<double>::iterator it;
for (it = xv.begin(); it < xv.end(); it++)
{
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
../src/CProcessData.cpp: In member function ‘int CProcessData::calculateMidPoints(const std::vector<double>&, const std::vector<double>&)’:
../src/CProcessData.cpp:44:9: error: no match for ‘operator=’ (operand types are ‘std::vector<double>::iterator {aka __gnu_cxx::__normal_iterator<double*, std::vector<double> >}’ and ‘__gnu_cxx::__normal_iterator<const double*, std::vector<double> >’)
Run Code Online (Sandbox Code Playgroud)
我会帮助你!
xv
是一个const
引用,意味着只能const
在其中调用成员函数.返回a 的const
重载,并且不能用于构造,因为它会破坏const-coreectness.std::vector<double>::begin()
const_iterator
iterator
所以你需要
std::vector<double>::const_iterator it;
Run Code Online (Sandbox Code Playgroud)
请注意,从C++ 11开始,您还有其他选择:
for (auto it = xv.begin(); it < xv.end(); it++)
Run Code Online (Sandbox Code Playgroud)
或者,如果您迭代所有元素,基于范围的循环可能会更好:
for (auto x: xv) { ... // x is a copy
for (auto& x: xv) { ... // x is a reference
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1059 次 |
最近记录: |