this 질문에 대한 첫 번째 대답에 따르면, 아래의 펑터는 foreach
으로 전달 된 후에 값을 유지할 수 있어야합니다 (이 예에서는 컴파일 할 때 struct Accumulator
을 얻을 수 없어 클래스가 작성되었습니다).함수는 std :: for_each에 전달 될 때 값을 유지할 수 있습니까?
// 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;
_cards
(예 당)
class Accumulator
{
public:
Accumulator(): counter(0){}
int counter;
void operator()(const Card & c) { counter += i; }
};
사용 예는 std::deque<Card>
로서 구현된다. _cards
이 얼마나 길어도 for_each
이 완료되면 acc.counter
은 0입니다. 내가 디버거에서 단계별로 카운터 증가를 볼 수 있지만, 그래서 그것은 값으로 전달되는 acc
과 관련이 있습니까?
간단한 개념으로 카운터를 사용하여 개념을 설명했습니다. 사실 내가 원하는 것은'faceup'과'facedown' 값을 유지하는 것입니다. 즉, deque를 반복하고 deque의 각 카드를 쿼리하여 얼굴 수를 위아래로 유지하는 것입니다. – BeeBand
Functor에서 정적 변수를 사용하는 것은 어떻습니까? – ALOToverflow
안녕하세요. 그것의 동일한 질문 http://stackoverflow.com/questions/2102056/foreach-doesnt-this-work-as-int –