问题描述
嗨!
我们假设我有这个
typedef std :: list< std :: string> string_list;
string_list sl;
如果我想遍历这个,我通常会这样做:
string_list :: iterator i = sl.begin();
while(i!= sl.end())
{
//做一些工作
}
这会检查sl中的所有字符串,因为end()给迭代器指向
后的位置元素。
现在我想做一些不同的事情:
string_list :: iterator j = sl.end();
bool is_good = true;
while(j!= sl.begin()&& is_good)
{
is_good = IsGood(* j);
if(is_good)j--;
}
但是,这个在sl中取出第一个字符串unbrocked(因为begin()给出
指向第一个元素的迭代器),所以在循环之后我必须这样做:
if(is_good )is_good = IsGood(* j);
有没有办法通过string_list向后遍历但是为了避免这种情况
额外检查(在循环中做一切)?
是的。使用reverse_iterator:
string_list :: reverse_iterator j = sl.rbegin();
bool is_good = true;
while (j!= sl.rend()&& is_good)
{
// ...
}
-
Matthias Kaeppler
习惯做法就是做这样的事情:
string_list :: reverse_iterator i = sl.rbegin();
while(i!= sl.rend( ))
{
//做一些工作
}
你可能会认出这段代码作为您的代码的一小部分变化
。当然,你可能不应该在每个循环中调用''end()''或
''rend()'',而是做这样的事情:
for(string_list :: reverse_iterator it = sl.rbegin(),end = sl.rend();
it!= end; ++ it)
{
//做一些工作
}
嗯,想一想:在很多情况下你可以使用其中一个现有的
算法参数化以满足您的需求。
-
< mailto:di ********** *@yahoo.com> < http://www.dietmar-kuehl.de/>
< http://www.contendix.com> - 软件开发&咨询
Hi!
Let''s assume I have this
typedef std::list<std::string> string_list;
string_list sl;
If I want to traverse through this, I usually do this:
string_list::iterator i = sl.begin();
while (i != sl.end())
{
// do some work
}
This checks all strings in sl because end() gives iterator pointing to
position after the last element.
Now I want to do something a bit different:
string_list::iterator j = sl.end();
bool is_good = true;
while (j != sl.begin() && is_good)
{
is_good = IsGood (*j);
if (is_good) j--;
}
But, this leaves first string in sl unchecked (because begin() gives
iterator pointing to first element), so after looping I must do this:
if (is_good) is_good = IsGood (*j);
Is there a way to traverse backwards through string_list but to avoid this
additional check (do everything in loop)?
Yes. Use a reverse_iterator:
string_list::reverse_iterator j = sl.rbegin();
bool is_good = true;
while( j != sl.rend() && is_good )
{
// ...
}
--
Matthias Kaeppler
The idiomatic approach is to do something like this:
string_list::reverse_iterator i = sl.rbegin();
while (i != sl.rend())
{
// do some work
}
You may recognize this code as being a small variation of code
of yours. Of course, you should probably not call ''end()'' or
''rend()'' in each loop but rather do something like this:
for (string_list::reverse_iterator it = sl.rbegin(), end = sl.rend();
it != end; ++it)
{
// do some work
}
Hm, thinking of it: in many cases you can use one of the existing
algorithms parameterized to do what you need.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting
这篇关于序列容器的向后遍历:停止条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!