gpt4 book ai didi

c++ - 如何在函数内部定义仿函数

转载 作者:可可西里 更新时间:2023-11-01 18:26:50 26 4
gpt4 key购买 nike

有时,我需要一些仿函数助手来操作列表。我尽量将范围保持在本地。

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
struct Square
{
int operator()(int x)
{
return x*x;
}
};

int a[5] = {0, 1, 2, 3, 4};
int b[5];

transform(a, a+5, b, Square());

for(int i=0; i<5; i++)
cout<<a[i]<<" "<<b[i]<<endl;
}

hello.cpp: In function ‘int main()’:
hello.cpp:18:34: error: no matching function for call to ‘transform(int [5], int*, int [5], main()::Square)’

如果我将 Square 移出 main(),没问题。

最佳答案

你做不到。但是,在某些情况下,您可以使用 boost::bindboost::lambda 库来构建仿函数,而无需声明外部结构。此外,如果您有最新的编译器(例如 gcc 4.5 版),您可以启用新的 C++0x 功能,允许您使用 lambda 表达式,允许这样的语法:

transform(a, a+5, b, [](int x) -> int { return x*x; });

关于c++ - 如何在函数内部定义仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6883892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com