c erase函数用法
时间: 2024-06-14 11:07:19 浏览: 16
C++中的erase函数用于删除字符串中的字符或子字符串。它有多种用法,具体取决于参数的类型和数量。
以下是erase函数的三种常见用法:
1. 删除指定位置的字符:
```cpp
string str = "This is an example phrase.";
str.erase(10, 8);
cout << str << endl; // 输出:"This is an phrase."
```
在上述示例中,erase函数从索引位置10开始,删除8个字符,即删除了"example "。
2. 删除指定位置的单个字符:
```cpp
string str = "This is an example phrase.";
string::iterator it = str.begin() + 9;
str.erase(it);
cout << str << endl; // 输出:"This is a phrase."
```
在上述示例中,erase函数使用迭代器指定要删除的字符的位置,即删除了第10个字符。
3. 删除指定范围的字符:
```cpp
string str = "This is an example phrase.";
str.erase(str.begin() + 5, str.end() - 7);
cout << str << endl; // 输出:"This phrase."
```
在上述示例中,erase函数使用迭代器指定要删除的字符范围,即删除了从第6个字符到倒数第8个字符之间的所有字符。
相关问题
c++写erase的用法
C语言中的erase函数并不存在,可能您想要了解的是C++中的erase函数,它是用于删除容器中指定位置或指定范围内的元素的函数。例如,可以使用vector容器的erase函数删除指定位置的元素,语法如下:
vector<int> vec = {1, 2, 3, 4, 5};
vec.erase(vec.begin() + 2); // 删除第三个元素,即数字3
这样就可以删除vector容器中的第三个元素,即数字3。
C++ unordered_set相关函数用法
C unordered_set 是 C++ STL 中的一个容器,用于存储无序不重复的元素。常用的函数包括 insert、erase、find、size、empty 等。其中 insert 函数用于插入元素,erase 函数用于删除元素,find 函数用于查找元素,size 函数用于获取元素个数,empty 函数用于判断容器是否为空。此外,C unordered_set 还支持迭代器,可以使用 begin 和 end 函数获取迭代器,从而遍历容器中的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)