Discussion: about end() usage
Afficher un message
Vieux 02/07/2008, 16h13   #5
Jerry Coffin
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut 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() such
> > > 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 accident.
> >
> > The following will work, and will produce the same result if 'b' is a key:
> >
> > Â Â it = mymap.upper_bound('b');
> > Â Â while (it != mymap.begin()) {
> > Â Â Â Â --it;
> > Â Â Â Â cout << (*it).first << " => " << (*it).second << endl;
> > Â Â }
> >
> > If 'b' is not a key, then this version will differ from yours in that the
> > first output will be the last key less than 'b' rather than the first key
> > 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 {
ostream &operator<<(ostream &os, mytype const &v) {
return os << v.first << " => " << v.second;
}
}

int main() {

std::map<char, int> mymap;

for (int i=0; i<10; i++)
mymap['b'+i] = i+1;

std::cout << "searched key is first item in map:\n";
std::reverse_copy(mymap.begin(), mymap.upper_bound('b'),
std:stream_iterator<mytype>(std::cout, "\n"));

mymap['a'] = 0;

std::cout << "\nSearched item is not first item in map:\n";
std::reverse_copy(mymap.begin(), mymap.upper_bound('b'),
std:stream_iterator<mytype>(std::cout, "\n"));
return 0;
}

--
Later,
Jerry.

The universe is a figment of its own imagination.
  Réponse avec citation
 
Page generated in 0,06116 seconds with 9 queries