C?++迭代器iterator在string中使用方法介紹
一、正向迭代器
【例子】
//正向迭代器 void test1() { string str1 = "abcdef"; cout << "讀取字符串:" << endl; string::iterator it1 = str1.begin(); while (it1 != str1.end()) { cout << *it1 << " "; it1++; } cout << endl; cout << "每個(gè)字母向后移動(dòng)一位:" << endl; string::iterator it2 = str1.begin(); while (it2 != str1.end()) { *it2 +=1; cout << *it2 << " "; it2++; } cout << endl; }
【運(yùn)行結(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; }
【運(yùn)行結(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; }
到此這篇關(guān)于C ++迭代器iterator在string中使用方法介紹的文章就介紹到這了,更多相關(guān)C ++迭代器iterator內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++中std::find函數(shù)介紹和使用場(chǎng)景
std::find函數(shù)是一個(gè)非常實(shí)用的通用查找算法,適用于各種場(chǎng)景,本文主要介紹了C++中std::find函數(shù)介紹和使用場(chǎng)景,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02c++使用regex報(bào)錯(cuò)regex_error兩種解決方案
C++正則表達(dá)式是一個(gè)非常強(qiáng)大和實(shí)用的工具,但是使用它們時(shí)需要注意仔細(xì)檢查代碼是否符合語法規(guī)則,這篇文章主要給大家介紹了關(guān)于c++使用regex報(bào)錯(cuò)regex_error的兩種解決方案,需要的朋友可以參考下2024-03-03MFC控件之CListCtrl的應(yīng)用實(shí)例教程
這篇文章主要介紹了MFC控件中CListCtrl的應(yīng)用方法,包括了針對(duì)表格的一些操作,是MFC中比較重要的一個(gè)控件類,需要的朋友可以參考下2014-08-08C++實(shí)現(xiàn)并優(yōu)化異常系統(tǒng)
異常處理是C++的一項(xiàng)語言機(jī)制,用于在程序中處理異常事件,下面這篇文章主要給大家介紹了關(guān)于C++中異常的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08