On May 6, 11:58 am, Ian Collins <ian-n...@[EMAIL PROTECTED]
> wrote:
> S S wrote:
> > I have a very basic question, but it's a good one. Below is
> > the code fragment.
> > struct ltstr
> > {
> > bool operator()(const char* s1, const char* s2) const
> > {
> > return strcmp(s1, s2) < 0;
> > }
> > };
> > int main()
> > {
> > const int N =3D 6;
> > const char* a[N] =3D {"isomer", "ephemeral", "prosaic",
> > "nugatory", "artichoke", "serif"};
> > set<const char*, ltstr> A(a, a + N);
> > if (A.find("ephemeral") !=3D A.end())
> > cout << "Found";
> > else
> > cout << "Not found";
> > return 0;
> > }
> > Output will be -> "Found"
> > My question is , Why?
> > How it is able to compare a const char* with another const char* to
> > find that value? I did not specify any equality operator? I just
> > mentioned strcmp(s1, s2) < 0
> > which means, when strcmp(s1, s2) =3D=3D 0 (in case of match)
> > it will return false. So how set/map are able to find the const char*
> > value?
> Given an ordered set, A < B < C and a search item X,
> if (X < C) and !(B < X) then X is equivalent to B.
The issue in std::set is a bit more complicated, because the
domain may include elements which are not members of std::set.
Basically, set<>::find first locates an element i such that for
all previous elements j, j < x, and i for i, !(i < x) (which
implies that the same holds for all following elements, of
course). Having found this i, if !(x < i) determines whether
the elements are equivalent or not: if !(i < x) && !(x < i), the
elements are considered to be equivalent.
Note the "considered to be". You can easily define an operator<
which is inconsistent with =3D=3D. (He has, in fact: his ltstr is
inconsistent with =3D=3D over char const*. Of course, if he were
also interested in =3D=3D, he'd define an eqstr, which returned
strcmp(s1, s2) =3D=3D 0.)
--
James Kanze (GABI Software) email:james.kanze@[EMAIL PROTECTED]
en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34


|