作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当满足 std::list
中的条件时,我试图删除列表中的元素。我在引用资料中读到关于 erase
函数返回值的内容:
An iterator pointing to the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.
Member type iterator is a bidirectional iterator type that points to elements.
我把这个例子放在一起:
#include <string>
#include <list>
#include <iostream>
int main()
{
typedef std::list<std::string> string_list_t;
string_list_t list;
list.push_back("test1");
list.push_back("test2");
list.push_back("test3");
list.push_back("test4");
list.push_back("test5");
list.push_back("test6");
list.push_back("test7");
list.push_back("test8");
for (string_list_t::iterator it = list.begin(); it != list.end(); ++it)
{
std::string &str = *it;
std::cout << "Checking " << str << "..." << std::endl;
if (str == "test4")
{
std::cout << "Found test4!" << std::endl;
}
else
{
it = list.erase(it);
}
}
return 0;
}
它没有给我预期的输出,而是给了我:
Checking test1...
Checking test3...
Checking test5...
Checking test7...
谁能帮我弄清楚我理解错了什么?它以某种方式跳过了第二个元素...
最佳答案
您正在跳过已删除元素之后的元素。
您应该使用 其中之一 it = list.erase(it);
或 ++it
,但不能同时使用。
关于c++ - 在迭代器中从 std::list 中移除一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42132798/
我正在做一个项目,我的 android 在这个项目中作为一个网络服务器工作;输入带端口号的 IP 地址,打开 Web 界面,用户可以将文件上传到手机。我想在 Web 界面上显示一些图片,以便我们的界面
我是一名优秀的程序员,十分优秀!