简体   繁体   English

如何为类方法提供STL容器以进行延迟评估?

[英]How to provide an STL container to a class method for lazy evaluation?

I'm trying to implement a parallel data gathering with consequent single-task data processing. 我正在尝试通过随后的单任务数据处理实现并行数据收集。 Parallel task would gather data into a number of vectors then pass the collected containers into a single-task processing class. 并行任务会将数据收集到多个向量中,然后将收集的容器传递到单任务处理类中。 Once all the gatherers complete the data gathering, the processing stage would commence. 所有收集者完成数据收集后,处理阶段将开始。

However, I'm confused at how to implement a processing class members that would hold the gathered data. 但是,我对如何实现将保存收集到的数据的处理类成员感到困惑。 I cannot make them references to vectors because references should be initialized at the processing object initialization time. 我不能使它们引用向量,因为引用应在处理对象初始化时初始化。 I probably cannot make them pointers to vectors because pointer fiddling is discouareged. 我可能无法使它们指向矢量的指针,因为不鼓励使用指针摆弄。 I also cannot make them another bunch of vectors to avoid the unnecessary data copying during the assignment operations. 我也不能使它们成为另一堆向量,以避免在分配操作期间不必要的数据复制。

How should I design the internals of the processing class to bypass those limitations? 我应该如何设计处理类的内部结构以绕过这些限制?

The answer is in your question - "...gather data into a number of vectors then pass the collected containers..." 答案就在您的问题中-“ ...将数据收集到多个向量中,然后传递收集的容器...”

You can make your internal data structures std::vector and pass the outside data using move and swap them with the internal vectors: 您可以创建内部数据结构std::vector并使用move传递外部数据,并将其与内部向量交换

class foo
{
    public:
        void set_vector(std::vector<int>&& vector)
        {
            std::swap(internal_vector, vector);
        }

        void alternative_set_vector(std::vector<int>& vector)
        {
            std::swap(internal_vector, vector);
        }

    private:
        std::vector<int> internal_vector;
};

void use_foo()
{
    foo some_foo;
    {
        std::vector<int> outside_vector;//fill outside_vector with your data
        some_foo.set_vector(std::move(outside_vector));
    }
    {
        std::vector<int> outside_vector;//fill outside_vector with your data
        some_foo.alternative_set_vector(outside_vector);
    }
}

The version with alternative_set_vector works fine, but it's not obvious for the calling code that the vector will be "filled" with some "random" values after the call. 带有alternative_set_vector的版本alternative_set_vector正常工作,但是对于调用代码而言,在调用之后将向量“填充”一些“随机”值并不明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM