64,636
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(void)
{
string a = "1234500000";
reverse(a.begin(), a.end()); // 先将字符串反转
cout << a << endl;
// 一下是处理用迭代器删除元素是,迭代器失效的典型做法
for(string::iterator iter = a.begin(); iter != a.end(); ) // 把++iter移动到循环体内
{
if(*iter == '0')
{
iter = a.erase(iter); // 删除一个元素后,iter会指向被删元素的下一个元素,
// 因此在这里不需要再++iter
}
else
{
++iter;
}
}
reverse(a.begin(), a.end()); // 再反转回去
cout << a << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a;
a = "1234500000";
for (string::iterator s = a.end() - 1;s != a.begin();s--)
{
if (*s == '0')
{
a.erase(s); //这里改一下,不能用a.erase(*s)
if (*(s-1) != '0')
break;
}
}
cout <<a << endl;
return 0;
}