我以前不经常使用STL,但我开始使用这个huffman压缩项目。除了"for_each“函数之外,似乎所有的东西都能正常工作,除了一个函数参数。因为我通常不使用xcode (我通常使用eclipse cdt),所以我不确定问题出在我的代码还是xcode上。
这是Huff.h文件
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();
};这是Huff.cpp文件中不起作用的部分。
//---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";
}发布于 2012-06-30 21:13:07
for_each(freq.begin(), freq.end(), copy_to); //I've also tried this->copy_tocopy_to是不能传递给std::for_each的成员函数。
你需要的是一个可调用的实体,它不需要隐式的this:这样的实体可以是函数式的,也可以是自由函数的,在C++11中,也可以是lambda。
如果您可以使用lambda解决方案,那么它将非常简单:
for_each(freq.begin(),
freq.end(),
[this](c_pair & c) { this->copy_to(c); } ); 在这里了解lambda表达式:
发布于 2012-06-30 21:21:36
正如所指出的,您不能在for_each中以这种方式使用成员函数。
C++03的替代方法是使用mem_fun和bind1st来构建函数对象:
std::for_each(freq.begin(), freq.end(),
std::bind1st(std::mem_fun(&Huff::copy_to), this));或者使用Boost.Bind
std::for_each(freq.begin(), freq.end(),
boost::bind(&Huff::copy_to, this, _1));https://stackoverflow.com/questions/11274303
复制相似问题