除了iterator 类型每个容器还定义了一个const iterator 类型,后者对于遍历const 容器
是必需的const iterator 允许以只读方式访问容器的底层元素,例如
#include <vector >
void even_odd( const vector<int> *pvec,
vector<int> *pvec_even,
vector<int> *pvec_odd )
{
// 必须声明一个const_iterator, 才能够遍历pvec
vector<int>::const_iterator c_iter = pvec->begin();
vector<int>::const_iterator c_iter_end = pvec->end();
for ( ; c_iter != c_iter_end; ++c_iter )
if ( *c_iter % 2 )
pvec_odd->push_back( *c_iter );
else pvec_even->push_back( *c_iter );
}
void print(const vector<int> *vec,vector<int>*vec_even,vector<int>*vec_odd)
{
vector<int>::const_iterator ite_be=vec->begin();
vector<int>::const_iterator ite_end=vec->end();
for(;ite_be!=ite_end;ite_be++)
{
if(*ite_be%2)
vec_even->push_back(*ite_be);
else
vec_odd->push_back(*ite_be);
}
};
这个是错误的。
void print(const vector<int> vec,vector<int>vec_even,vector<int>vec_odd)
{
vector<int>::const_iterator ite_be=vec.begin();
vector<int>::const_iterator ite_end=vec.end();
for(;ite_be!=ite_end;ite_be++)
{
if(*ite_be%2)
vec_even.push_back(*ite_be);
else
vec_odd.push_back(*ite_be);
}
};
调用
vector<int>vec_even;
vector<int>vec_odd;
print(&vec,&vec_even,&vec_odd);
vector<int>::iterator ite_be=vec_even.begin();
for(;ite_be!=vec_even.end();++ite_be)
{
cout<<*ite_be<<endl;
}
vector<int>vec_even2;
vector<int>vec_odd2;
print(vec,vec_even2,vec_odd2);
for(vector<int>::iterator ite_be=vec_even2.begin();ite_be!=vec_even2.end();++ite_be)
{
cout<<*ite_be<<endl;
}