函数体可以在函数体内本地定义吗?在代码体内定义仿函数
为本地定义函子我能想到的,(特别是如果我们想用STL算法),是说
我们有两个向量std::vector<int>
的a
和b
一个可能的用途话,可以考虑他们平等在许多方面。即a[i] = b[i] (mod loop_counter)
其中loop_counter不断变化,我们测试它们在每次循环迭代中的相等性。
for(int i=0 ; i<=10 ; ++i)
{
//Define binary predicate functor my_local_predicate
//Test for equality using functor local to loop
std::equal(a.begin(), a.end(), b.begin, my_local_predicate)
// Do something if they are equal OR unequal
}
如果答案是否定的,那么对于平等的条件在每次迭代中不断变化的情况,上述方法将如何进行?
注意:我试着定义一个仿函数如下(这里没有for
循环)但程序无法编译。
#include <algorithm>
#include <iostream>
#include <list>
int main() {
class EvenOddFunctor
{
int even_;
int odd_;
public:
EvenOddFunctor() : even_(0), odd_(0) {}
void operator()(int x) {
if (x%2 == 0) even_ += x;
else odd_ += x;
}
int even_sum() const { return even_; }
int odd_sum() const { return odd_; }
};
EvenOddFunctor evenodd;
int my_list[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
evenodd = std::for_each(my_list,
my_list+sizeof(my_list)/sizeof(my_list[0]),
evenodd);
std::cout << "Sum of evens: " << evenodd.even_sum() << "\n";
std::cout << "Sum of odds: " << evenodd.odd_sum() << std::endl;
// output:
// Sum of evens: 30
// Sum of odds: 25
}
在main()
代码编译干净,并正确地执行之前移动所述算符定义。
所以,即使在一个函数体内定义一个仿函数似乎是不可能的,我还是希望能够在每次迭代中改变相等条件的方式来实现一些不错的STL。
您正在使用哪种C++编译器?如果它足够新,那么lambda可能是您的一个选择。 – JaredPar 2012-01-13 00:22:39
[为什么使用本地结构作为STL函数参数的代码不能在g ++中编译?](http://stackoverflow.com/questions/4569928/why-code-using-local-struct-as-parameter-for -stl-function-does-not-compile-in-g) – 2012-01-13 00:23:09
可能的重复[什么是C++ 11中的lambda表达式?](http://stackoverflow.com/questions/7627098/what-is-a -lambda-expression-in-c11) – Flexo 2012-01-13 00:23:32