加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 函数可以在传递给std :: for_each时保留值吗?

发布时间:2020-12-16 10:16:12 所属栏目:百科 来源:网络整理
导读:根据 this问题的第一个答案,下面的仿函数应该能够在传递给foreach后保留一个值(我无法在示例中获取struct Accumulator进行编译,因此构建了一个类). class Accumulator{ public: Accumulator(): counter(0){} int counter; void operator()(const Card c) { c
根据 this问题的第一个答案,下面的仿函数应该能够在传递给foreach后保留一个值(我无法在示例中获取struct Accumulator进行编译,因此构建了一个类).

class Accumulator
{
    public:
        Accumulator(): counter(0){}
        int counter;
        void operator()(const Card & c) { counter += i; }
};

示例用法(根据示例)

// 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实现为std :: deque< Card>.无论_cards获得多长时间,在for_each完成后acc.counter为零.当我在调试器中单步执行时,我可以看到计数器递增,但是,它是否与acc通过值传递有关?

解决方法

这只是 asked here.

原因是(正如您猜测的那样)std :: for_each复制其仿函数并调用它.但是,它也返回它,因此如上面链接的答案中所述,使用for_each的返回值.

也就是说,你只需要使用std::accumulate

int counter = std::accumulate(_cards.begin(),0);

仿函数和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(),is_face_up());
int faceDown = 52 - faceUp;

并使用C 0x lambda来获得乐趣(仅仅因为):

int faceUp = std::count_if(_cards.begin(),[](const Card& pC){ return pC.isFaceUp(); });

好多了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读