我有一段这样的代码:
std::list<boost::shared_ptr<Point> > left, right;
// ... fill lists ...
// now, calculate the angle between (right[0], right[1]) and (right[0], left[0])
double alpha = angle(*(right.begin()->get()), *(((++right.begin()))->get()), *(left.begin()->get()) );
std::cout << alpha * 180 / M_PI << std::endl;
if(alpha < 0){
    // do something with the lists, like reversing them. Especially the beginning and end of the lists may change in some way, but "left" and "right" are not reassigned.
}
// calculate the new alpha
alpha = angle(*(right.begin()->get()), *(((++right.begin()))->get()), *(left.begin()->get()) );
除了迭代器增量魔法,这里没有评论可能不是太obvoius,我想定义一个函数double alpha()来减少重复.但是因为这个函数的使用非常具体,所以我想把它作为一个局部函数.理想情况是这样的:
int a, b;
int sum(){ return a + b; }
a = 5; b = 6;
int s = sum(); // s = 11
a = 3;
s = sum(); // s = 9 now
在像Python这样的语言中,这将是完全可以的,但如何在C++中执行此操作?
编辑:
这就是我最终的结果,特别感谢@wilx和-std=c++0x编译器标志:
auto alpha = [&right, &left]() {
    // not 100% correct due to my usage of boost::shared_ptr, but to get the idea
    Point r_first = *(right.begin()); 
    Point l_first = *(left.begin());
    Point r_second = *(++right.begin());
    return angle(r_first, r_second, l_first);
};
if(alpha() < 0) // fix it
double new_alpha = alpha();
在这种情况下,我建议使用像angle2(std::list<Point> const &, etc.). 两个简单的论点比你现在所拥有的要好。
在 C++11 中,您可以使用 lambda 通过引用捕获其参数。
如果您无法使用 C++11 并且确实喜欢冒险,请尝试 Boost.Phoenix(Boost.Spirit 的一部分)。