1 回答
TA贡献1773条经验 获得超3个赞
对于vector一般不要用erase(),因为很多情况下他要和<algorithm>中的remove()一块用!erase()的使用会使迭代器失效如果删除的不是最后面的元素的话。你的程序中if(*iter%2==0)
ivec.erase(iter);
可以换成:(记着加头文件<algorithm>)
if
(*iter%2
==
0)
ivec.erase(remove(ivec.begin(),
ivec.end(),
*iter),
ivec.end())
但如果你用if
(*iter%2
!=
0)
ivec.erase(remove(ivec.begin(),
ivec.end(),
*iter),
ivec.end())
输出结果则包含11,结果错误!
不知道你为什么数组,向量,链表都用,为了和你一致,我也只能改成这样:
#include
<iostream>
#include
<vector>
#include
<list>
#include
<algorithm>
#include
<functional>
#include
<iterator>
using
namespace
std;
int
main
()
{
vector<int>
ivec;
list<int>
ilis;
int
vec[]
=
{2,
3,
4,
5,
6,
7,
8,
9,
10,
11};
remove_copy_if
(vec,
vec+10,
back_inserter(ivec),
bind2nd(modulus<int>(),
2));
remove_copy_if
(vec,
vec+10,
back_inserter(ilis),
not1(bind2nd(modulus<int>(),
2)));
for
(vector<int>::const_iterator
iter
=
ivec.begin();
iter
!=
ivec.end();
++iter)
cout
<<
*iter
<<
'\t';
cout
<<
endl;
for
(list<int>::const_iterator
liter
=
ilis.begin();
liter
!=
ilis.end();
++liter)
cout
<<
*liter
<<
'\t';
cout
<<
endl;
}
最好的做法是:
#include
<iostream>
#include
<vector>
#include
<list>
#include
<algorithm>
#include
<functional>
#include
<iterator>
using
namespace
std;
int
main
()
{
vector<int>
ivec,
odd_vec,
even_vec;
for
(int
i
=
2;
i
!=
12;
++i)
ivec.push_back(i);
remove_copy_if
(ivec.begin(),
ivec.end(),
back_inserter(even_vec),
bind2nd(modulus<int>(),
2));
remove_copy_if
(ivec.begin(),
ivec.end(),
back_inserter(odd_vec),
not1(bind2nd(modulus<int>(),
2)));
copy
(even_vec.begin(),
even_vec.end(),
ostream_iterator<int>(cout,
"\t"));
cout
<<
endl;
copy
(odd_vec.begin(),
odd_vec.end(),
ostream_iterator<int>(cout,
"\t"));
cout
<<
endl;
}
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报