65,210
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <list>
#include <string>
using namespace std;
int main()
{
string one[3] = {"rty", "ab", "bc"};
list<string> two(one, one+3);
list<string>::iterator p;
for(p=two.begin(); p!=two.end(); ++p)
{
if((*p)>"a") //是不是这里比较出错了?C++中字符串不是可以直接比较吗?
{
two.erase(p);
}
}
p = two.begin();
for(int i=0; i<two.size(); i++)
{
cout<<*p<<endl;
p++;
}
return 0;
}
#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <list>
#include <string>
using namespace std;
bool greater_then_b(const string &s)
{
return s > string("b");
}
int main()
{
string one[3] = {"rty", "ab", "bc"};
list<string> two(one, one+3);
list<string> three(one, one+3);
list<string>::iterator p;
for(p=two.begin(); p!=two.end(); )
{
if((*p)>"b") //是不是这里比较出错了?C++中字符串不是可以直接比较吗?
// 比较没错,关键在于erase之后 p 成非法的啦, erase返回被删除元素之后的元素
{
p = two.erase(p);
} else {
++p;
}
}
p = two.begin();
for(int i=0; i<two.size(); i++)
{
cout<<*p<<endl;
p++;
}
// 其实用remove_if是最简单的
three.remove_if(greater_then_b);
p = three.begin();
for(int i=0; i<three.size(); i++)
{
cout<<*p<<endl;
p++;
}
return 0;
}