Click to See Complete Forum and Search --> : How to manage member function pointers correctly?


HighCommander4
February 5th, 2005, 03:52 PM
I'm getting some weird errors when I'm trying to pass a pointer-to-member-function argument to an STL function like transform(). Here's a simplified version of the code I'm trying to compile:

class myclass
{
private:
vector<int> vec1;
...
int some_function(int x) { return x + 1; }
public:
void member_function()
{
transform(vec1.begin(), vec1.end(), vec1.begin(), some_function);
}
...
};

I am certain that the errors stem from the fact that the last argument to transform() is a pointer to a member function, because if I make some_function a non-member function, the code compiles and works. However, I can't make some_function() a non-member function because I need it to be only accessible from within myclass.

What is the correct way to pass a member function pointer argument to an STL function?

Graham
February 5th, 2005, 05:42 PM
Look up std::mem_fun.

(Sorry for terse reply - short on time)

HighCommander4
February 6th, 2005, 02:14 PM
mem_fun wasn' exactly what I was looking for, but that's all right. I simply made some_function() static, and now it works. :cool:

I have another, related question about the transform() algorithm:

#include <map>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
string names[5] = { "one", "two", "three", "four", "five" };
int numbers[5] = { 1, 2, 3, 4, 5 };
map<string, int> mymap;
transform(names, names + 5, numbers,
insert_iterator<map<string, int> >(mymap, 0), make_pair);
return 0;
}

I'm trying to make use of the second version of transform() that takes 5 arguments, iterators marking the beginning and end of one range, an interator markign the beginning of a second range, an iterator marking the beginning of an outout range and a binary functor that takes an element from the first range and one from the second range as arguments, and outputs the result to the output range.

However, my compiler gives an error about no matching function call. Is it something about make_pair() that doesn't allow it to be used in this fashion?