如果遇到常量容器类型,需要使用迭代器的时候,那么必须使用常量迭代器——const_iterator
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <string>
#include <array>
using namespace std;
#define LENGTH 10
typedef int TYPE;
typedef vector<TYPE> VECTORTYPE;
typedef deque<TYPE> DEQUETYPE;
typedef list<TYPE> LISTTYPE;
typedef forward_list<TYPE> FORWARD_LISTTYPE;
typedef array<TYPE,LENGTH> ARRAYTYPE;
void print(VECTORTYPE & );
void print(DEQUETYPE & );
void print(LISTTYPE & );
void print(FORWARD_LISTTYPE & );
void print(ARRAYTYPE & );
void print(string &);
void print(list<string> &);
int main()
{
list<string> names;
vector<const char*> oldstyle = {"asdf","asdf"};
//names = oldstyle;wrong ,type is not matching
names.assign(oldstyle.begin(),oldstyle.end());
print(names);
const list<const char*> c_str{"const string1","const string2","const string3"};
//因为c_str是常量迭代器,它的迭代器必须是常量迭代器类型:const_iterator,例如下面会报错
for(list<const char*>::iterator i = c_str.begin(); i != c_str.end(); ++i)
cout << *i << " ";
return 0;
}
void print(VECTORTYPE &vec)
{
for(VECTORTYPE::iterator i = vec.begin() ; i != vec.end() ; ++i)
{ cout << *i << " ";}
cout << endl;
return ;
}
void print(DEQUETYPE &vec)
{
for(DEQUETYPE::iterator i = vec.begin() ; i != vec.end() ; ++i)
{ cout << *i << " ";}
cout << endl;
return ;
}
void print(LISTTYPE &vec)
{
for(LISTTYPE::iterator i = vec.begin() ; i != vec.end() ; ++i)
{ cout << *i << " ";}
cout << endl;
return ;
}
void print(FORWARD_LISTTYPE &vec)
{
for(FORWARD_LISTTYPE::iterator i = vec.begin() ; i != vec.end() ; ++i)
{ cout << *i << " ";}
cout << endl;
return ;
}
void print(ARRAYTYPE &vec)
{
for(ARRAYTYPE::iterator i = vec.begin() ; i != vec.end() ; ++i)
{ cout << *i << " ";}
cout << endl;
return ;
}
void print(string & s_vec)
{
for(string::iterator i = s_vec.begin(); i != s_vec.end() ; ++i)
{cout << *i << " ";}
cout << endl;
}
void print( list<string> &l)
{
for(list<string>::iterator i = l.begin();i != l.end();++i)
cout << *i << " ";
cout << endl;
}
//上述代码会在g++编译器中报错:
r@r-Sys:~/c++/9/now$ ./123
asdf asdf
const string1 const string2 const string3 r@r-Sys:~/c++/9/now$ g++ 11.cc -o 123
11.cc: In function ‘int main()’:
11.cc:33:50: error: conversion from ‘std::__cxx11::list<const char*>::const_iterator {aka std::_List_const_iterator<const char*>}’ to non-scalar type ‘std::__cxx11::list<const char*>::iterator {aka std::_List_iterator<const char*>}’ requested
for(list<const char*>::iterator i = c_str.begin(); i != c_str.end(); ++i)
修改方法是:把代码中提示的那里的iterator改成:const_iterator即可 |