c string的erase刪除方法

2021-10-02 15:56:52 字數 1376 閱讀 2524

之前不是很清楚c++中string如何刪除元素,現在記錄一下。

(參考自 c++ primer plus 第六版 模版類 string)

string中提供的成員函式可以用來刪除字串中的字元,這裡主要介紹erase方法

1. basic_string & erase(size_type pos=0, size_type n=npos);

即從給定起始位置pos處開始刪除, 要刪除字元的長度為n, 返回值修改後的string物件引用

示例[1]

#include

#include

using

namespace

std;

int main()

輸出

刪除迭代器位置處的單個字元, 並返回下個元素的迭代器

刪除迭代器[first, last)區間的所有字元,返回乙個指向被刪除的最後乙個元素的下乙個字元的迭代器.

示例[2,3]:

#include

#include

using namespace std;

int main()

輸出

除了erase方法用於刪除string中的元素,void pop_back();方法也可以用來刪除元素, 但是只能刪除string的最後乙個元素

查詢方法

在使用erase刪除函式的時候,經常會和查詢函式一起使用

*find*(**)系列方法引數可以是char 或者 string 型別, 為待查詢的目標, 返回值為 size_type;當 查詢不到目標時,返回值為 npos, 可以這樣判斷

string longer("that's a funny hat.");

//size_type loc1 = longer.find("hat"); // 存在

size_type loc1 = longer.find("hello"); //不存在

if (loc1 == string:

:npos)

cout<< "not found"

<

c string的erase刪除方法

之前不是很清楚c 中string如何刪除元素,現在記錄一下。參考自 c primer plus 第六版 模版類 string string中提供的成員函式可以用來刪除字串中的字元,這裡主要介紹erase方法 1.basic string erase size type pos 0,size type...

vector呼叫erase刪除元素

for std vector iterator iter g vecdownloadinfos.begin iter g vecdownloadinfos.end else pop back 只刪除最後乙個元素,而erase可以刪掉乙個由iterator指出的元素,也可刪掉乙個範圍的元素 remov...

vector中使用erase刪除元素

很容易受陣列的影響,寫出如下 std vecotr iterator it vc.begin for it vc.end it 原因是vector中在刪除乙個元素後,迭代器會自動指向下乙個元素。所以,上面的 很可能導致迭代器越界。the c standard library 中解釋 c.erase ...