CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Aug 1999
    Location
    Montreal, Quebec
    Posts
    132

    std::for_each question.

    Hello to all,

    Here we go :

    Suppose I have a function that takes an int as the only parameter and returns nothing. Let's call it Func1(int).

    Suppose, next, that I have a std::vector<int> named coll.

    Is there any way to call Func1 for each element in the vector ???

    Here's what I tried :
    Code:
    std::for_each(coll.begin(), coll.end(), std::mem_fun(&Func1));
    This doesn't work. I've looked at the bind2st algo in the std but i'm not sure how it works. Can someone help me on this please.

    Thanks in advance for any help.

    Luc.

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    Should this work ?

    Code:
    std::for_each(coll.begin(), coll.end(),Func1);
    Usually mem_fun is used if you are sorting a
    vector of objects, and you want to call a
    member function of that object.

  3. #3
    Join Date
    Aug 1999
    Location
    Montreal, Quebec
    Posts
    132
    Might I add that Func1 is a method of a class.

    Like this :
    Code:
    ActualRealPos::Func1(int)
    {
    //does something.
    }
    
    ActualRealPos::Init()
    {
    std::vector<int> coll;
    
    std::for_each(coll.begin(), coll.end(), std::mem_fun(&ActualRealPos::Func1));
    }

  4. #4
    Join Date
    Feb 2002
    Posts
    5,757
    Do you want to modify each element as it is passed into Func1()? for_each() is non-mutatable. One solution is transform().

    Kuphryn

  5. #5
    Join Date
    Aug 1999
    Location
    Montreal, Quebec
    Posts
    132
    Nope, I only want to call Func1 for each value that are in the vector.

    Thanks,

    Luc.

  6. #6
    Join Date
    Feb 2002
    Posts
    5,757
    Here is an example of an function object adaptor.

    Code:
    template <typename T>
    class FunctionObjectAdaptor : public std::unary_function<T, void>
    {
       public:
             void operator()(const T lp) const
             {
                ...
             }
    };
    Kuphryn

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured