Re: about end() usage
In article <94394196-cb35-4d7f-9754-
ba7280cab66d@h1g2000prh.googlegroups.com>, zhangyefei.yefei@gmail.com
says...
On Jul 1, 10:43 pm, "Andrew Koenig" <a...@acm.org> wrote:
<zhangyefei.ye...@gmail.com> wrote in message
news:deae0df6-bed0-4f70-9f8d-56c5ab2a16cd@u36g2000prf.googlegroups.com.=
...
can someone tell me ,is the following about end() right ? =
the
printed result seems ok,but i am not sure if i can use end() su=
ch
way.
it=mymap.lower_bound ('b'); // it points to b
for ( ; it != mymap.end(); it--)
cout << (*it).first << " => " << (*it).second << endl;
This isn't legitimate; if it happens to do what you want, it's an accid=
ent.
The following will work, and will produce the same result if 'b' is a k=
ey:
it = mymap.upper_bound('b');
while (it != mymap.begin()) {
--it;
cout << (*it).first << " => " << (*it).se=
cond << endl;
}
If 'b' is not a key, then this version will differ from yours in that t=
he
first output will be the last key less than 'b' rather than the first k=
ey
greater than 'b'.
the question is that if "it" happens to be the first element (that
is mymap.begin() ),then we can not access the first
element,nothing is outputed.
#include <map>
#include <iostream>
#include <algorithm>
typedef std::pair<char, int> mytype;
// technically not allowed...
namespace std {
=09ostream &operator<<(ostream &os, mytype const &v) {
=09=09return os << v.first << " => " << v.second;
=09}
}
int main() {
=09std::map<char, int> mymap;
=09for (int i=0; i<10; i++)
=09=09mymap['b'+i] = i+1;
=09std::cout << "searched key is first item in map:\n";
=09std::reverse_copy(mymap.begin(), mymap.upper_bound('b'),
=09=09std::ostream_iterator<mytype>(std::cout, "\n"));
=09mymap['a'] = 0;
=09std::cout << "\nSearched item is not first item in map:\n";
=09std::reverse_copy(mymap.begin(), mymap.upper_bound('b'),
=09=09std::ostream_iterator<mytype>(std::cout, "\n"));
=09return 0;
}
--
Later,
Jerry.
The universe is a figment of its own imagination.