std :: for_each,object with operator()重载不维护状态 [英] std::for_each, object with operator() overloaded not maintaining state

查看:117
本文介绍了std :: for_each,object with operator()重载不维护状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试回答这个问题我想出了以下代码:

In trying to answer this question I came up with the following code:

#include <string>
#include <iostream> 
#include <algorithm>
#include <vector>

class Sizes
{
public:
    void operator() ( std::vector<int> v ) { 
        sizeVec.push_back( v.size() );  
    }
    std::vector<int> sizeVec;
};

void outFunc (int i) {
    std::cout << " " << i;
}
int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<std::vector<int>> twodVec;

    std::vector<int> vec;
    vec.push_back( 6 );
    twodVec.push_back( vec );
    vec.push_back( 3 );
    twodVec.push_back( vec );
    vec.push_back( 8 );
    twodVec.push_back( vec );
    vec.push_back( 3 );
    twodVec.push_back( vec );

    Sizes sizes;
    std::for_each( twodVec.begin(), twodVec.end(), sizes );
    std::for_each( sizes.sizeVec.begin(), sizes.sizeVec.end(), outFunc );

    return 0;
}



随着每个呼叫按预期增加。但是当第二个std :: foreach被调用的时候,sizeVec是空的...我已经创建了一个工作,涉及传递一个向量到Sizes,但任何人都知道发生了什么

Debugging this shows Sizes::operator() being called and the size of sizeVec increasing with each call as expected. However when the second std::foreach is called the sizeVec is empty... I've created a work around involving passing a vector into Sizes but does anyone know what's going on

推荐答案

std :: for_each 通过值接受函数,而不是 em>,因此原始对象不受影响。您需要:

std::for_each takes a functor by value, not by reference, so the original object is unaffected. You need to do:

sizes = std::for_each( twodVec.begin(), twodVec.end(), sizes );

这篇关于std :: for_each,object with operator()重载不维护状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆