passing objects from for_each() to calling function

I want to insert each element in a vector into a hash table. I am doing that by for_each in <algorithm> header file, which calls insert() function, which inserts each element passed, into a hash table. Problem is, the hash table that insert() instantiates, would be local to that insert() function. How do I return the populated hash table back to the calling function?
Last edited on
Use boost::ref() on the hash table instance.

1
2
3
4
5
std::vector<int> v( 10, 5 );
std::list<int> l;

std::for_each( v.begin(), v.end(),
    boost::bind( &std::list<int>::push_back, boost::ref( l ), _1 ) );

With for_each you can use a function object
eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct myFunc
{
    hash_table_type *ptrToMyHashTable;

    myFunc ( hash_table_type *ptrToMyHashTable ) : ptrToMyHashTable (ptrToMyHashTable) {}

    void operator() ( element_type el ) // Will be called from for_each
    {
         //insert el in your hash table
    }
};

//...
hash_table_type MyHashTable;

for_each ( myVector.begin(), myVector.end(),  myFunc ( &MyHashTable )/*create an object of myFunc*/ );
Thanks Bazzy, Its working now.

Is myFunc object created and destroyed with every element of myVector? If so, is it going to suffer from "shallow copy" problem?

<EDIT> The first questions still remains. <EDIT>
Thanks.
Last edited on
Jsmith, I want to try boost::bind() solution also. Which header file do I need to include in order to run BOOST on MS Visual C++ 2008?

Thanks.
Goto boost.org and get the latest stuff. You can also go to boostpro.org and get a quick installer from there as well.
It will be in

boost/bind.hpp

if you have/once you have boost installed.
Can I have access to the iterator position for the element passed within myFunc above? For example, if I am passing value pointed by 1st iterator to myFunc, is there anyway I can locate next element to the 1st iterator passed, which is second element, within my Func?

Thanks!
No. The function supplied as the last parameter to for_each is given a T not an iterator to a T.
What do you think is the best way to solve the problem:

- A vector of integers is given. Program should Reduce the vector of integers by cumulatively applying a function to every two digits, starting from the beginning and return final result.

For example: vector A = 1,2,3,4,5
Program calculates ((((1+2)+3)+4)+5) and returns final result

where + is a "function". It should work for any function.
1
2
3
4
5
assert( v.size() >= 2 );
int result = v[0];
for( size_t i = 1; i < v.size(); ++i )
    result = func( result, v[i] );
return result;

Thanks!!
Topic archived. No new replies allowed.