如果list作为常量参数传入函数时,使用list的迭代器要注意,如果代码这样写:
ostream& operator<<(ostream& ostr,const list<int>& li){ list<int>::iterator it=li.begin(); while(it!=li.end()){ ostr<<" "<<*it; it++; } return ostr; }
会得到错误提示:
[Error] conversion from 'std::list<int>::const_iterator {aka std::_List_const_iterator<int>}' to non-scalar type 'std::list<int>::iterator {aka std::_List_iterator<int>}' requested
大概意思是无法把const_iterator转换为iterator。
带着问题查看一下,list的实现源码,发现,list居然有两个begin()函数,分别如下:
// iterators /** * Returns a read/write iterator that points to the first element in the * %list. Iteration is done in ordinary element order. */ iterator begin() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_node._M_next); } /** * Returns a read-only (constant) iterator that points to the * first element in the %list. Iteration is done in ordinary * element order. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_node._M_next); }
出错原因明白了,因为传入的参数为const,所以调用的是第二个函数,返回的是const_iterator,而不是iterator,才会报错。
在原有基础上做如下修改即可正确运行,
ostream& operator<<(ostream& ostr,const list<int>& li){ list<int>::const_iterator it=li.begin(); while(it!=li.end()){ ostr<<" "<<*it; it++; } return ostr; }
就是再声明迭代器是,由原来的:list<int>::iterator it 改为:list<int>::const_iterator it
一个完整的代码:演示list中sort函数的用法,list无法使用algorithm的sort:
#include<iostream> #include<functional> #include<list> using namespace std; ostream& operator<<(ostream& ostr,const list<int>& li){ list<int>::iterator it=li.begin(); while(it!=li.end()){ ostr<<" "<<*it; it++; } return ostr; } int main(){ list<int>li; li.push_back(6); li.push_back(8); li.push_back(2); li.push_back(9); li.push_back(1); li.push_back(4); cout<<"before: "<<li<<" "; li.sort(); cout<<"ascending: "<<li<<" "; li.sort(greater<int>()); cout<<"descending: "<<li<<" "; return 0; }