这是计算子阵列的最大总和的函数
int Solution::maxSubArray(const vector<int> &A) {
vector<int>::iterator i;
int max_so_far = *A.begin();
int current_max = *A.begin();
for(i = A.begin(); i != A.end(); ++i)
{
current_max = max(*i,*i+current_max);
max_so_far = max(max_so_far,current_max)
}
return max_so_far;
}
这是错误,我得到的是C ++ 11,而不是以前的版本。帮我解决这个问题
solution.cpp: In member function 'int Solution::maxSubArray(const std::vector<int>&)':
solution.cpp:9:8: error: no match for 'operator=' (operand types are 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' and 'std::vector<int>::const_iterator {aka __gnu_cxx::__normal_iterator<const int*, std::vector<int> >}')
for(i = A.begin(); i != A.end(); ++i)
^
solution.cpp:9:8: note: candidates are:
In file included from /usr/include/c++/4.8/bits/stl_algobase.h:67:0,
from /usr/include/c++/4.8/bits/char_traits.h:39,
from /usr/include/c++/4.8/ios:40,
from /usr/include/c++/4.8/ostream:38,
from /usr/include/c++/4.8/iostream:39,
from solution.h:7,
from solution.cpp:-3:
/usr/include/c++/4.8/bits/stl_iterator.h:708:11: note: __gnu_cxx::__normal_iterator<int*, std::vector<int> >& __gnu_cxx::__normal_iterator<int*, std::vector<int> >::operator=(const __gnu_cxx::__normal_iterator<int*, std::vector<int> >&)
class __normal_iterator
^
/usr/include/c++/4.8/bits/stl_iterator.h:708:11: note: no known conversion for argument 1 from 'std::vector<int>::const_iterator {aka __gnu_cxx::__normal_iterator<const int*, std::vector<int> >}' to 'const __gnu_cxx::__normal_iterator<int*, std::vector<int> >&'
/usr/include/c++/4.8/bits/stl_iterator.h:708:11: note: __gnu_cxx::__normal_iterator<int*, std::vector<int> >& __gnu_cxx::__normal_iterator<int*, std::vector<int> >::operator= (__gnu_cxx::__normal_iterator<int*, std::vector<int> >&&)
/usr/include/c++/4.8/bits/stl_iterator.h:708:11: note: no known conversion for argument 1 f
答案 0 :(得分:10)
您需要使用vector<int>::const_iterator
代替vector<int>::iterator
。
如果您使用的是支持C ++ 11或更高版本的编译器,则可以使用auto
类型。
auto i = A.begin();
答案 1 :(得分:3)
你不能使用常规迭代器来通过const向量。
vector<int>::iterator i
必须为::const_iterator i
。
请参阅此问题What is the difference between const_iterator and non-const iterator in the C++ STL?
答案 2 :(得分:0)
迭代器必须是const_iterator
,参数为const vector<int>
更改行
vector<int>::iterator i;
到
vector<int>::const_iterator i;
或使用auto
获取类型
答案 3 :(得分:0)
由于您将向量作为 const 传递,因此正常的迭代器无法完成工作。 相反,你需要 const_iterator 来获取 const vector 。
int Solution::maxSubArray(const vector<int> &A) {
vector<int>::const_iterator i;
for(i = A.begin(); i != A.end(); ++i)
{
....
}
那应该为你修好!