解决error C2440: “初始化”: 无法从“std::_List_const_iterator<_Mylist>”转换为“std::_List_iterator<_Mylist>”

来源:互联网 发布:淘宝卖刀为什么能寄 编辑:程序博客网 时间:2024/06/06 10:35
学习C++时,当使用vector、list的常量做为某函数的参数时,如
void ListPrint(const list<int> &lt){list<int>::iterator iter = lt.begin();while(iter != lt.end()){cout << *iter << endl;}}
会报如下错误
error C2440: “初始化”: 无法从“std::_List_const_iterator<_Mylist>”转换为“std::_List_iterator<_Mylist>”

查看list源码后发现list.begin()有两个函数

iterator begin(){// return iterator for beginning of mutable sequencereturn (iterator(this->_Nextnode(this->_Myhead), this));}

const_iterator begin() const{// return iterator for beginning of nonmutable sequencereturn (const_iterator(this->_Nextnode(this->_Myhead), this));}

因为传入的参数为const,所以调用的是第二个函数,返回的是const_iterator,而不是iterator,才会报错。

在原有基础上做如下修改即可正确运行

void ListPrint(const list<int> &lt){list<int>::const_iterator iter = lt.begin();//iterator修改为const_iteratorwhile(iter != lt.end()){cout << *iter << endl;}}

0 0
原创粉丝点击