Yahoo Clever wird am 4. Mai 2021 (Eastern Time, Zeitzone US-Ostküste) eingestellt. Ab dem 20. April 2021 (Eastern Time) ist die Website von Yahoo Clever nur noch im reinen Lesemodus verfügbar. Andere Yahoo Produkte oder Dienste oder Ihr Yahoo Account sind von diesen Änderungen nicht betroffen. Auf dieser Hilfeseite finden Sie weitere Informationen zur Einstellung von Yahoo Clever und dazu, wie Sie Ihre Daten herunterladen.

Need help with for_each in C++!?

Hello

I want to use for_each in C++

This works without for_each algo.

for (GardenPlan::iterator it = plan.begin(); it != plan.end() ; ++it ){

(*it)->print(cout);

}

I've a vector with pointer of shapes. shape has this memberfuction void print(std::ostream &os) const;

I tried this piece of code, but i wont work:

for_each(plan.begin(), plan.end(), bind2nd(mem_fun(&Shape::print ) , os) );

thanks 4 help

Update:

btw os is cout.

Update 2:

problem is that it doesnt compile.

The pointer Typ is "std::tr1::shared_ptr<Shape>" .

2 Antworten

Relevanz
  • ?
    Lv 7
    vor 1 Jahrzehnt
    Beste Antwort

    mem_fun is not compatible with shared_ptr. Since you have TR1, use TR1:

    #include <tr1/memory>

    #include <tr1/functional>

    #include <algorithm>

    ...

         using namespace std::tr1::placeholders;

         for_each(plan.begin(), plan.end(),

             bind(&Shape::print, _1, std::tr1::ref(os)));

    incidentally, if your compiler is new enough, C++0x (in which std::bind2nd has been officially deprecated in favor of std::bind, by the way) can make it more readable with lambdas:

         for_each(plan.begin(), plan.end(),

             [&os](std::shared_ptr<Shape> p){ p->print(os); });

  • vor 1 Jahrzehnt

    what exactly is the problem? is bind2nd not called?

    also print appears to be __thiscall so it needs a valid class pointer.

Haben Sie noch Fragen? Jetzt beantworten lassen.