根据这个问题的第一个答案,下面的仿函数应该能够在传递之后保留一个值foreach(我无法struct Accumulator在示例中进行编译,因此构建了一个类).
class Accumulator
{
public:
Accumulator(): counter(0){}
int counter;
void operator()(const Card & c) { counter += i; }
};
Run Code Online (Sandbox Code Playgroud)
示例用法(根据示例)
// Using a functor
Accumulator acc;
std::for_each(_cards.begin(), _cards.end(), acc);
// according to the example - acc.counter contains the sum of all
// elements of the deque
std::cout << acc.counter << std::endl;
Run Code Online (Sandbox Code Playgroud)
_cards实现为std::deque<Card>.无论多长时间_cards,完成acc.counter后为零for_each.当我在调试器中单步执行时,我可以看到计数器递增,但是,它是否与acc通过值传递有关?
这只是在这里问的.
原因是(正如您猜测的那样)std::for_each复制其仿函数并调用它.但是,它也返回它,因此如上面链接的答案中所述,使用返回值for_each.
也就是说,你只需要使用std::accumulate:
int counter = std::accumulate(_cards.begin(), _cards.end(), 0);
Run Code Online (Sandbox Code Playgroud)
一个仿函数,for_each这里不正确.
对于您的使用(计算一些,忽略其他人),您可能需要提供自己的仿函数并使用count_if:
// unary_function lives in <functional>
struct is_face_up : std::unary_function<const Card&, const bool>
{
const bool operator()(const card& pC) const
{
return pC.isFaceUp(); // obviously I'm guessing
}
};
int faceUp = std::count_if(_cards.begin(), _cards.end(), is_face_up());
int faceDown = 52 - faceUp;
Run Code Online (Sandbox Code Playgroud)
并使用C++ 0x lambda来获得乐趣(仅仅因为):
int faceUp = std::count_if(_cards.begin(), _cards.end(),
[](const Card& pC){ return pC.isFaceUp(); });
Run Code Online (Sandbox Code Playgroud)
好多了.