cpp list库删除特定数
时间: 2023-08-22 09:09:38 浏览: 45
在C++ STL的list容器中,您可以使用`std::list::remove()`函数删除list容器中所有等于特定值的元素。以下是一些示例代码:
```cpp
#include <iostream>
#include <list>
int main() {
std::list<int> mylist = { 1, 2, 3, 4, 5 };
mylist.remove(3);
std::cout << "The list after removing all nodes with value 3:" << std::endl;
for (auto& x : mylist) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
```
在上面的代码中,我们使用`std::list::remove()`函数删除所有值为3的节点。最后,我们遍历整个list容器,并将其输出到控制台。
需要注意的是,`std::list::remove()`函数将删除list容器中所有等于特定值的元素,并返回void。如果您只想删除list容器中的第一个等于特定值的元素,则可以使用`std::list::erase()`函数和一个指向该元素的迭代器。以下是一些示例代码:
```cpp
#include <iostream>
#include <list>
int main() {
std::list<int> mylist = { 1, 2, 3, 4, 5 };
auto it = std::find(mylist.begin(), mylist.end(), 3);
if (it != mylist.end()) {
mylist.erase(it);
std::cout << "The list after removing the node with value 3:" << std::endl;
for (auto& x : mylist) {
std::cout << x << " ";
}
std::cout << std::endl;
}
else {
std::cout << "The node with value 3 is not found in the list." << std::endl;
}
return 0;
}
```
在上面的代码中,我们使用`std::find()`函数查找值为3的节点,并使用`std::list::erase()`函数删除该节点。最后,我们遍历整个list容器,并将其输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)