Link to home
Start Free TrialLog in
Avatar of Kitty__Kong
Kitty__Kong

asked on

using for_each to to push items onto a queue

i want to turn this

for( u = 0; u < graph.size(); ++u )
            Q.push( &graph[u] );

into 1 line using for_each

for_each( graph.begin(), graph.end(), bind1st( mem_fun( &priority_queue<VERTEX*, vector<VERTEX*>, VERTEX >::push ), &Q ) );

soemthing like that is the idea but i cant get it to work. how do i fix it?
Avatar of Indrawati
Indrawati

OK, not sure if this is your problem here, but I always have problem using mem_fun on a member function that takes argument(s) on VC++6 (compiler error) . It seems ok though on member function that does not expect any argument.
Download the boost libraries from www.boost.org

Now you can write:

    std::for_each(graph.begin(),graph.end(),
                  boost::lambda::bind(&priority_queue<VERTEX*, vector<VERTEX*>, VERTEX >::push,&Q,&boost::lambda::_1));

after adding

#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>

to your list of includes
Avatar of Kitty__Kong

ASKER

im using vsnet2k3

i want to to do it without boost
i forgot to say graph is a vector<VERTEX>

#include <functional>
#include <algorithm>
#include <queue>
#include <vector>
 
using namespace std;
 
int main()
{
   priority_queue<int> q;
   vector<int> g;
 
   for_each(g.begin(), g.end(),
       bind1st(mem_fun(&priority_queue<int>::push), &q));
 
    return 0;
}

there is a simple example of wht i want to work
It's certainly possible to construct something that you can pass to for_each and accomplish the desired goal, but I don't think you can do it in one line.  It would have to be a function object that knows about the queue.  You can write a class for such objects, but I don't think you can whip it up out of standard library functions as you are trying to do.

But you never know, some other expert may yet enlighten us all.

--efn
ASKER CERTIFIED SOLUTION
Avatar of anthony_w
anthony_w
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
so what i want is impossible using just the stl? it cant be made to work using functional?
> so what i want is impossible using just the stl? it cant be made to work using functional?

That's my opinion.  I just hesitate to be too dogmatic, because the library is so big and obscure.

By the way, to call a member function of an object passed by reference, you can use mem_fun_ref.  But that doesn't help with this problem.

In addition to the solutions anthony_w showed, it would be possible to craft one using bind1st or bind2nd.  But like those, it would require several lines.

--efn
im going to leave the question up a bit longer to see if someone comes up with a way to do what i want. if no one does i will accept one of the already posted responses.