C++使用变换(STL)时出错
我在使用转换时遇到编译错误:
它与我之前的问题有关: C++:如何将字符串对象复制到 int 数组?)
enter code here
class BinaryCode {
public:
int get_digit(char c)
{
return c-'0';
}
void decode(string decd)
{
int i;
std::vector<int>decoded(decd.size());
std::transform(decd.begin(), decd.end(), decoded.begin(), get_digit);
int length=decoded.length();
错误是:
enter code here
[root@localhost topcoder]# g++ prog1.c
prog1.c: In member function `void BinaryCode::decode(std::string)':
prog1.c:20: error: argument of type `int (BinaryCode::)(char)' does not match `int (BinaryCode::*)(char)'
有人可以帮助我吗?我正在使用 gcc (g++) 编译器。
I am facing a compilation error on using transform:
It is related to my previous question: C++: How to copy a string object to an int array?)
enter code here
class BinaryCode {
public:
int get_digit(char c)
{
return c-'0';
}
void decode(string decd)
{
int i;
std::vector<int>decoded(decd.size());
std::transform(decd.begin(), decd.end(), decoded.begin(), get_digit);
int length=decoded.length();
The error is:
enter code here
[root@localhost topcoder]# g++ prog1.c
prog1.c: In member function `void BinaryCode::decode(std::string)':
prog1.c:20: error: argument of type `int (BinaryCode::)(char)' does not match `int (BinaryCode::*)(char)'
Can anyone please help me? I am using a gcc (g++) compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
恕我直言,最好的方法是将其定义更改为
它
应该与此(静态函数)一起使用。可以使用成员函数进行转换,但稍微复杂一些。而且,你不需要它。
The best IMHO would be to change the definition of
to
It should work with this (static function). It is possible to transform using member functions, but it's slightly more complicated. Moreover, you don't need it.
您需要传递函数或函子作为最后一个参数,而不是成员函数。如果您启用了 c++11,则可以使用 lambda :
由于您没有 c++11 功能,因此您可以将 get_digit, 转换为函数(在类之外):
或创建一个函子:
You need to pass a function or functor as the last parameter, not a member function. If you have c++11 enabled, you can use lambda :
Since you do not have c++11 features, you can convert get_digit, into a function (outside of the class):
or create a functor :
1>
您可以将 get_digit 移到 BinaryCode 之外,然后您的代码就可以工作
2>
或者如果你希望 get_digit 成为一个非静态成员函数,那么你可以使用
3> 当然,如果你可以访问 boost 或 c++11,那么你可以轻松地使用 lambda,就像其他人已经向你展示的那样。
1>
You can either move the get_digit outside the BinaryCode then your code would work
2>
or if you want get_digit to be a non-static member function, then you can use
3>of course if you have access to either boost or c++11, then you can easily use lambda as others have already showed u.