【C++】string类对象的迭代遍历及元素访问操作
📌string类对象的迭代遍历及元素访问操作
string类对象的迭代器相关函数共有8个,如下:
编辑
string类对象的元素访问相关函数共有四个,如下:
编辑
接下来我们演示学习几种常见的string类对象的迭代遍历及元素访问函数:
函数名称 |
功能说明 |
|
operator[] |
返回pos位置的字符,const string类对象调用 |
|
begin+end |
begin获取一个字符的迭代器+end获取最后一个字符下一个位置的迭代器 |
|
rbegin+rend |
begin获取一个字符的迭代器+end获取最后一个字符下一个位置的迭代器 |
|
范围for |
C++支持更简洁的范围for的新遍历方式 |
🎏operator[]运算符重载
operator[]运算符重载定义:operator[]文档链接
编辑
operator[]遍历string类对象:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string st1("Hello world");
for (size_t i = 0; i < st1.size(); i++)
{
cout << st1[i] << endl;
}
return 0;
}
operator[]遍历效果如下:编辑
operator[]修改string类对象:
因为operator[]返回的是引用类型,因此可以利用其对string对象进行修改:
int main()
{
string st1("Hello world");
for (size_t i = 0; i < st1.size(); i++)
{
++st1[i];
cout << st1[i] << endl;
}
return 0;
}
编辑
operator[]重载访问string类对象和内置类型访问数组成员的区别:编辑
🎏顺序迭代器begin+end
begin+end迭代器顺序遍历访问字符串:
begin()函数定义如下:
编辑
end()函数定义如下:编辑
begin+end迭代器顺序遍历访问string类对象:
int main()
{
string st1("Hello world");
//迭代器
string::iterator it = st1.begin();
while (it != st1.end())
{
cout << *it << endl;
++it;
}
return 0;
}
begin+end迭代器顺序遍历访问效果如下:
编辑
begin+end迭代器修改string类对象:
int main()
{
string st1("Hello world");
//迭代器
string::iterator it = st1.begin();
while (it != st1.end())
{
++(*it);
cout << *it << endl;
++it;
}
return 0;
}
begin+end迭代器修改string类对象效果如下:编辑
🎏反向迭代器rbegin+rend
rbegin+rend逆序遍历访问string类对象:
rbegin()函数定义如下:
编辑
rend()函数定义如下:
编辑
使用rbegin+rend迭代器反向遍历访问string类对象:
int main()
{
string st1("Hello world");
//反向迭代器
string::reverse_iterator rit = st1.rbegin();
while (rit != st1.rend())
{
cout << *rit << endl;
++rit;
}
return 0;
}
rbegin+rend迭代器反向遍历访问string类对象效果如下:
编辑
使用rbegin+rend反向迭代器修改string类对象:
int main()
{
string st1("Hello world");
//反向迭代器
string::reverse_iterator rit = st1.rbegin();
while (rit != st1.rend())
{
++(*rit);
cout << *rit << endl;
++rit;
}
return 0;
}
rbegin+rend反向迭代器修改string类对象效果如下:
编辑
🎏范围for
C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量, 第二部分则表示被迭代的范围。(注:知道数据类型的情况下可以不使用auto关键字自动推导类型)
范围for顺序访问string类对象:
int main()
{
string st1("Hello world");
for (auto ch : st1)
{
cout << ch << endl;
}
return 0;
}
范围for顺序访问string类对象效果如下:
编辑
范围for修改string类对象:
int main()
{
string st1("Hello world");
for (auto &ch : st1)
{
ch++;
cout << ch << endl;
}
return 0;
}
范围for修改string类对象效果如下:
编辑
注:范围for在底层会替换成迭代器!
- 点赞
- 收藏
- 关注作者
评论(0)