Huibuh wrote:
I start hating RETURN!!!
You'd be screwed without it.
[...]
// What you are about to see is a reconstruction.
// It's also a complete, compilable translation unit.
// Please check "How to post" in the FAQ.
#include <list>
#include <iostream>
#include <ostream>
struct happy
{
int number;
happy (int n = 0) : number (n) { }
};
// //THIS WAS MY LAST TRY
// // *** I hope you can follow my comments.
// happy* findhappy (list<happy> a, int now)
// // *** This copies the argument into the parameter element-
// // *** by-element. We often pass large objects _by reference_
// // *** rather than _by value_ (unless we need a local _copy_
happy * findhappy (std::list <happy> & a, int now)
{
// {
// ptr=a.begin();
// // *** We shan't need this iterator outside this scope
// // *** so we can declare it here:
std::list <happy>::iterator iter = a.begin ();
// nownumber=ptr.operator ->();
// *** Whoah there! "happy * nownumber = & * ptr;" would be easier
// *** to read; but wait a minute, we're not going to do it like this.
// while (nownumber->number!=now)
// {
// ptr=ptr.operator ++(); // *** Just "++ ptr;"
// nownumber=ptr.operator ->(); // *** Just "nownumber = & * ptr;"
// }
// return nownumber;
// }
// // *** The logic of this loop is all wrong. Get out a pencil
// // *** and paper and work out what would happen if the value
// // *** "now" is not present in a happy object in the list.
// // ***
// // *** The following works OK. We don't need to transform the
// // *** iterator into a pointer until just before we return
// // *** from the function, so that's what I do here.
// // *** I notice that we're simulating a "for" loop here.
// // *** Maybe you can change it for the real thing.
while (iter != a.end ())
{
if (iter->number == now)
return & (* iter );
++ iter;
}
return 0;
}
int main ()
{
std::list <happy> a;
a.push_back (happy (2));
a.push_back (happy (3));
a.push_back (happy (5));
if (happy * p = findhappy (a, 3))
{
std::cout << "Found a happy object with number "
<< p->number << ".\n";
}
else
{
std::cout << "Didn't find a matching happy object.\n";
}
}
--
Regards,
Buster.