[英]std::list::erase(iter) exception handling c++
我尝试从函数中获取一个迭代器,然后从列表中删除一个元素。
当我使用无效的迭代器运行程序时,它将引发以下异常:
Exception thrown: read access violation.
_Right.**_Myproxy** was 0xCCCCCCCC. occurred
我的功能是:
list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{
for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
{
if ((*j).phone == p) return j;
}
}
void RemoveAccount(list<AccountStruct>& Acc)
{
string Phone;
cout << "Enter Phone Number ->" << endl;
cin >> Phone;
//cout << "Searching..." << endl;
list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
try
{
Acc.erase(iter);
}
catch()// <- What to put inside??
{
cout << "No Phone Number;" << endl;
}
}
我们可以通过一些更改来解决此问题。 首先,如果函数找不到对象,则SearchAccount
不会返回任何内容。 这是未定义的行为,因为您必须在声明时返回某些内容。 如果find
该项目,我们可以通过返回end()
来解决此问题,就像find
一样。 那给你
list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{
for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
{
if ((*j).phone == p) return j;
}
return Acc.end(); // item not found
}
现在SearchAccount
可以正常运行了,我们可以检查是否返回了end()
而不是使用异常机制。 看起来像
void RemoveAccount(list<AccountStruct>& Acc)
{
string Phone;
cout << "Enter Phone Number ->" << endl;
cin >> Phone;
//cout << "Searching..." << endl;
list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
if (iter != Acc.end())
{
Acc.erase(iter);
}
else
{
cout << "No Phone Number;" << endl;
}
}
现在,您不再需要异常机制的开销,并且发生了“正确的事情”。
您应该使用::std::remove_if
算法
Acc.erase
(
::std::remove_if
(
Acc.begin()
, Acc.end()
, [&Phone](AccountStruct const & acc)
{
return(acc.phone == Phone);
}
)
, Acc.end()
);
std::list::erase
不会引发任何异常。
不需要try
块。 但是,无效的迭代器将导致未定义的行为。
你可以返回Acc.end()
在后的for
中环SearchAccount
和核对返回的值Acc.end
而不是使用try
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.