網(wǎng)站首頁 編程語言 正文
一、正向迭代器
【例子】
//正向迭代器
void test1()
{
string str1 = "abcdef";
cout << "讀取字符串:" << endl;
string::iterator it1 = str1.begin();
while (it1 != str1.end())
{
cout << *it1 << " ";
it1++;
}
cout << endl;
cout << "每個字母向后移動一位:" << endl;
string::iterator it2 = str1.begin();
while (it2 != str1.end())
{
*it2 +=1;
cout << *it2 << " ";
it2++;
}
cout << endl;
}
【運行結(jié)果】
二、正向迭代器(只讀數(shù)據(jù))
const_iterator begin( ) const;
這種迭代器,只支持讀,不支持修改數(shù)據(jù)。
【例子】
//只讀正向迭代器
void test2()
{
const string str1 = "abcdef";
cout << "只能讀取字符串:" << endl;
string::const_iterator it1 = str1.begin();
while (it1 != str1.end())
{
cout << *it1 << " ";
it1++;
}
cout << endl;
}
【問題】
為什么不能直接在 string::iterator it 前面加const?
答:這樣的話,const修飾的是it,it將無法被修改,并不是*it無法被修改。
it無法被修改的后果是無法遍歷。
三、反向迭代器
作用:從后往前讀。
【例子】
//反向迭代器
void test3()
{
string str1 = "abcdef";
cout << "反向讀取字符串:" << endl;
string::reverse_iterator it1 = str1.rbegin();
while (it1 != str1.rend())
{
*it1 += 1;
cout << *it1 << " ";
it1++;
}
cout << endl;
}
【運行結(jié)果】
四、反向迭代器(只讀)
【例子】
//反向迭代器(只讀)
void test4()
{
const string str1 = "abcdef";
cout << "反向只讀讀取字符串:" << endl;
string::const_reverse_iterator it1 = str1.rbegin();
while (it1 != str1.rend())
{
cout << *it1 << " ";
it1++;
}
cout << endl;
}
五、auto來替換這些特別長類型名
是不是感覺這些類型名特別長?別擔(dān)心,用auto試試。
//auto
void test5()
{
cout << "auto的演示" << endl;
const string str1 = "abcdef";
cout << "反向只讀讀取字符串:" << endl;
auto it1 = str1.rbegin();
while (it1 != str1.rend())
{
cout << *it1 << " ";
it1++;
}
cout << endl;
}
原文鏈接:https://blog.csdn.net/m0_54381284/article/details/127548820
相關(guān)推薦
- 2022-09-09 Qt?QFtp客戶端實現(xiàn)上傳下載文件_C 語言
- 2023-01-21 Python參數(shù)解析器configparser簡介_python
- 2023-05-23 golang中的單引號轉(zhuǎn)義問題_Golang
- 2023-01-08 Android的VSYNC機制和UI刷新流程示例詳解_Android
- 2022-10-08 ASP.NET泛型一之泛型簡介與基本語法_實用技巧
- 2022-12-25 Redis中AOF與RDB持久化策略深入分析_Redis
- 2022-07-22 mybatis源碼之集成springboot原理
- 2022-12-13 C++?POSIX?API超詳細(xì)分析_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支