求STL使用问题解释!

2 views
Skip to first unread message

邱戈川

unread,
Mar 6, 2006, 3:17:40 AM3/6/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
今天看c++ primer 3/e的时候看到有道练习题:6.12

int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
list<int> ilist( ia, ia+11 );
用单个iterator 形式的erase()删除ilist
中所有奇数位置的元素。

因为之前看过effective stl,所以知道答案应该是:

方法1):
bool badValue(int value)
{
if(value%2 == 1)
return true;

return false;
}

int main(int argc, char* argv[])
{
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 22, 55, 90 };
list<int> ilist( ia, ia+11 );

ilist.remove_if(badValue);
}

问题:我使用了sgi的stl但是编译有错:
error C2039: 'remove_if' : is not a member of 'list<int,class
std::__default_alloc_template<0,0> >'

请大家给个说明,谢谢!

方法 2):

用候捷的C++
Primer题解上的解释:(具体应该说是候捷网站上的讨论后的结果)
int main(int argc, char* argv[])
{
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 22, 55, 90 };
list<int> ilist( ia, ia+11 );

ilist.remove_if(bind2nd(modulus<int>(), 2));
}

问题:同1)

方法 3):
int main(int argc, char* argv[])
{
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 22, 55, 90 };
list<int> ilist( ia, ia+11 );

for(list<int>::iterator it = ilist.begin(); it != ilist.end(); )
{
if(*it%2 == 1)
{
it = ilist.erase(it);
}
else
{
++it;
}

}
}

这个就没有问题。

邱戈川

unread,
Mar 6, 2006, 10:23:46 PM3/6/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
今天用stlport试了试,3种方法都可以。
但是那个最优?有兴趣可以比对一下。

时代过客

unread,
Mar 12, 2006, 9:56:21 PM3/12/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
没深究过.不过建议尽量使用容量或算法里的方法进行迭代
Reply all
Reply to author
Forward
0 new messages