⚠️1⃣️string::npos是unsigned int,值为:18446744073709551615,如果用它给int赋值,转换为int值为-1;如果给unsigned int赋值,值为:4294967295.
2⃣️据说使用迭代器和erase可能导致后面元素的迭代器均失效,已开始总是出现段错误,以为是for循环条件的问题,以为是迭代器变动问题,想要确认一下:
1.当使用erase去掉一个元素时,sell.end()也会跟这变,不用担心for循环中的条件不对
2.防止erase失效的两种办法:it–,后++,或者不动it。或者it=buy.erase(it),会返回sell中it的下一个有效位置。
3⃣️这道题正真错的是it2=it2+sell.find(*it1)-1;,!!!这里不用减1,一位find返回的位置也是从0开始
心得:当你无论如何都觉得没错的时候,它就真的没错,错的很可能是你没注意到的。而最快的解决方法是输出各种程序中的控制流程的值,输出的好看点,然后按步骤看错在哪步
#include<iostream>
#include<string>
using namespace std;
int main()
{
string buy,sell;
cin>>sell>>buy;
for(string::iterator it1=buy.begin();it1!=buy.end();it1++)
{
string::iterator it2=sell.begin();
if(sell.find(*it1)!=string::npos)
{
it2=it2+sell.find(*it1)-1;
buy.erase(it1);
sell.erase(it2);
it1--;
}
}
if(buy.size()==0)
cout<<"Yes "<<sell.size()-buy.size()<<endl;
else
cout<<"No "<<buy.size()<<endl;
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
string buy,sell;
cin>>sell>>buy;
for(string::iterator it1=buy.begin();it1!=buy.end();)
{
string::iterator it2=sell.begin();
if(sell.find(*it1)!=string::npos)
{
it2+=sell.find(*it1);
it1=buy.erase(it1);
sell.erase(it2);
}
else
it1++;
}
if(buy.size()==0)
cout<<"Yes "<<sell.size()-buy.size()<<endl;
else
cout<<"No "<<buy.size()<<endl;
return 0;
}