0

I haven't used the STL much before, but I started to on this huffman compression project. Everything seems to work except the "for_each" function, which wont except a function argument. Since I don't normally use xcode (I usually use eclipse cdt) I'm not sure if the problem is with my code or with xcode.

This is the Huff.h file

class Huff {
private:
    typedef pair<char, int> c_pair;
    vector<Node> nodes;
    vector<Code> code;
    string content;
    void copy_to(c_pair c);
public:
    Huff(string);
    ~Huff();

    string compress();
    bool set_content();
    string get_content();
    string get_compress();
};

And this is the part of the Huff.cpp file that will not work.

//---Compress---

void Huff::copy_to(c_pair c){
    Node n(c.second, c.first, NULL, NULL);
    nodes.push_back(n);
}
string Huff::compress(){
    map<char, int> freq;
    for(int i = 0; i < content.length(); i++)
        freq[content[i]]++;
    for_each(freq.begin(), freq.end(), copy_to); //I've also tried this->copy_to
    return "110";
}
sinθ
  • 11,093
  • 25
  • 85
  • 121
  • 1
    Try this: `for_each(freg.begin(), freq.end(), mem_fun(&Huff::copy_to));` You need to include ``. – jrok Jun 30 '12 at 13:12
  • 1
    @mkb: No, that is not an answer. `std::mem_fun` doesn't know about the `this` pointer on which the member function is to be invoked. – Nawaz Jun 30 '12 at 13:33

2 Answers2

3
for_each(freq.begin(), freq.end(), copy_to); //I've also tried this->copy_to

copy_to is a member function which cannot be passed to std::for_each.

What you need is a callable entity which doesn't need implicit this : such an entity can be either functor or free function, and in C++11, lambda also.

The lambda solution would be pretty simple if you can use it:

for_each(freq.begin(), 
         freq.end(), 
         [this](c_pair & c) { this->copy_to(c); } ); 

Learn about lambda expression here:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

As pointed out, you can't use a member function that way with for_each.

The C++03 alternative is to use mem_fun and bind1st to build a function object:

std::for_each(freq.begin(), freq.end(), 
              std::bind1st(std::mem_fun(&Huff::copy_to), this));

Or using Boost.Bind:

std::for_each(freq.begin(), freq.end(), 
              boost::bind(&Huff::copy_to, this, _1));
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236