C++关于带有remove_if的指针/引用
我正在尝试使用remove_if 删除向量中的元素以进行过滤。问题是当我编译编码时,没有错误,但是当我尝试使用过滤器函数时,弹出错误说我无法取消引用迭代器。我不知道出了什么问题,希望你们能帮忙找出问题所在。 这是我的部分代码
bool filter_C (Teacher &t)
{
return (t.getCat() != compare); //compare is a static string
}
void filterTeacherCategory(vector<Teacher> &t)
{
vector<Teacher>::iterator i;
Teacher *ptr;
i = remove_if(t.begin(), t.end(), filter_C);
ptr = &(*i);
for (i = t.begin(); i != t.end(); ++i)
{
ptr->getName();
cout << "\t";
ptr->getGender();
cout << "\t";
ptr->getPhone();
cout << "\t";
ptr->getCategory();
cout << "\t\t";
ptr->getLocation();
cout << "\n";
}
}
I'm trying to use remove_if to remove elements in my vector to do filtering. The problem is when I compile the coding, there were no error but when I try to use the filter function, error popped out saying I can't dereference an iterator. I have no idea what is wrong and hope you guys can help spot the problem.
Here's partial of my codes
bool filter_C (Teacher &t)
{
return (t.getCat() != compare); //compare is a static string
}
void filterTeacherCategory(vector<Teacher> &t)
{
vector<Teacher>::iterator i;
Teacher *ptr;
i = remove_if(t.begin(), t.end(), filter_C);
ptr = &(*i);
for (i = t.begin(); i != t.end(); ++i)
{
ptr->getName();
cout << "\t";
ptr->getGender();
cout << "\t";
ptr->getPhone();
cout << "\t";
ptr->getCategory();
cout << "\t\t";
ptr->getLocation();
cout << "\n";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要实际删除元素,您需要执行类似
remove_if
的操作,只为您提供删除元素的范围(新结束)。在您的代码中,您的ptr
正是新的结尾(即,超过最后一个有效元素)。To actually erase elements, you need to do something like
remove_if
only provides you with a range (new end) with elements removed. And in your code yourptr
is exactly the new end (that is, one past the last valid element).remove_if 返回向量的新末尾。所以你应该像这样迭代
来自 remove_if 文档
一般来说,在remove_if之后删除剩余元素是个好主意
现在t.begin()和t.end()之间的所有内容都是有效且良好的,所以你可以这样做
remove_if returns the new end of the vector. so you should be iterating like so
From remove_if documenation
In general it is a good idea to erase the remaining elements after a remove_if
Now everything between t.begin() and t.end() is all valid and good so you can do
此行在
序列的过滤部分结束后取消引用元素。如果您的过滤器根本不匹配任何元素,因此没有删除任何内容,那么您将尝试将迭代器取消引用到向量末尾的迭代器,这将给出您报告的错误。即使不是,
i
指向的元素的内容也不太有帮助。根本不清楚你想要的
ptr
是什么,但我很确定它不是这个。This line
is dereferencing the element after the end of the filtered part of the sequence. If your filter didn't match any elements at all, so nothing was removed, then you're trying to dereference an iterator to one past the end of the vector, which will give the error you report. And even if not the contents of the element pointed to by
i
are not likely to be very helpful.It's not at all clear what you want
ptr
to be, but I'm pretty sure it's not this.