最近要用到, 先来写个程序(注意, 后来网友帮我发现, 如下这个程序有问题):
#include <iostream>
#include <map>
#include <string>
using namespace std;
void deleteAllMark(string &s, const string &mark)
{
unsigned int nSize = mark.size();
while(1)
{
unsigned int pos = s.find(mark);
if(pos == string::npos)
{
return;
}
s.erase(pos, nSize);
}
}
int main()
{
string s = " abc def ";
string b = "abcdef";
deleteAllMark(s, " ");
cout << ((s==b)? "yes": "no")<< endl;
return 0;
}
问题在哪里呢? 如上是32位(指编译机)机器, 上述程序是OK的, 但如果是64位(指编译机)机器, 就出现问题了:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::erase: __pos (which is 4294967295) > this->size() (which is 6)
Aborted
应该用更具有移植性质的size_t, 请用如下正确版本的程序:
#include <iostream>
#include <map>
#include <string>
using namespace std;
void deleteAllMark(string &s, const string &mark)
{
size_t nSize = mark.size();
while(1)
{
size_t pos = s.find(mark); // 尤其是这里
if(pos == string::npos)
{
return;
}
s.erase(pos, nSize);
}
}
int main()
{
string s = " abc def ";
string b = "abcdef";
deleteAllMark(s, " ");
cout << ((s==b)? "yes": "no")<< endl;
return 0;
}
修改后, 在32(指编译机)和64(指编译机)位机器上都OK. 再次感谢评论中的网友。
后面, 我会在博客中再次讨论这个问题。