string函数迭代器的使用
迭代器的声明:
string str("abcdefg");
//正向遍历str
std::string iterator it = str.begin(); //或end()
std::string const_iterator it = str.begin(); //或cend(),只读
//反向遍历str
std::string reverse_iterator r_it = str.rbegin(); //或rend()
std::string const_reverse_iterator cr_it = str.crbegin(); //或crend(),只读
在C++11中,支持auto语法,由编译器自动推测变量的类型,减少书写的麻烦
auto it = str.begin();
举例:
/*
>Plan:string的迭代器
>Author:ADiiana
>Time:2019/03/17
*/
#include<iostream>
#include<string>
using namespace std;
int main(){
string str("abcdefg");
cout << "正向遍历: ";
for (string::iterator it = str.begin(); it != str.end(); ++it){
cout << *it;
}
cout << endl;
//定义反向遍历迭代器
cout << "反向遍历: ";
for (string::reverse_iterator it = str.rbegin(); it != str.rend(); ++it)
cout << *it;
cout << endl;
//定义非const可以用迭代器改变string的值。
cout << "输出字符串大写,正向遍历: ";
for (string::iterator it = str.begin(); it != str.end(); ++it){
*it = *it - 'a' + 'A';
cout << *it;
}
cout << endl;
/* //编译报错: 不能给常量赋值
cout << "输出字符串大写,正向遍历: ";
for (string::const_iterator it = str.begin(); it != str.end(); ++it){
*it = *it - 'a' + 'A';
cout << *it;
}
cout << endl;
*/
system("pause");
return 0;
}