【问题标题】:C++: How do I write a function that accepts an iterator and inserts elements?C++:如何编写一个接受迭代器并插入元素的函数?
【发布时间】:2011-04-11 02:09:49
【问题描述】:
template<class Container>
void BlitSurface::ExtractFrames(Container & output, int frame_width, int frame_height,
                                         int frames_per_row, int frames_per_column,
                                         bool padding) const
{
    SDL_Surface ** temp_surf = SDL_Ex_ExtractFrames(_surface, frame_width, frame_height, frames_per_row, frames_per_column, padding);

    int surface_count = frames_per_row * frames_per_column;

    output.resize(surface_count);
    Container::iterator iter = output.begin();

    for(int i=0; i<surface_count; ++i, ++iter)
        iter->_surface = temp_surf[i];

    delete [] temp_surf;
}

我有这个功能将图像分割成帧并将它们存储到图像容器中。我将如何修改它以采用迭代器而不是容器,并在该点插入元素?

【问题讨论】:

    标签: c++ iterator containers


    【解决方案1】:

    使用back_inserter:

    template<typename OutputIterator>
    void BlitSurface::ExtractFrames(OutputIterator it, int frame_width, int frame_height,
                                             int frames_per_row, int frames_per_column,
                                             bool padding) const
    {
        /* ... other lines unchanged ...*/
        for(int i=0; i<surface_count; ++i) {
            // "BlitSurface()" sets other members to zero. Alternatively you
            // can use boost::value_initialized for that. 
            BlitSurface bs = BlitSurface();
            bs._surface = temp_surf[i];
            *it++ = bs;
        }
        delete [] temp_surf;
    }
    

    然后这样称呼它

    ExtractFrames(std::back_inserter(container), ...);
    

    【讨论】:

    • 每次看到这样的答案,我都知道我对 STL 知之甚少。 :(
    • 我这样做了:ExtractFrames(std::back_inserter(surface_vec), c_width, c_height, 16, 6, true); -------- 然后我收到以下错误:“错误 C2182:'v':非法使用类型 'void'”,“错误 C2440:'initializing':无法从 'value_type' 转换为 'int '”,还有一些其他的。 surface_vec 是一个 std::vector
    • @user 嗯,我的错。输出迭代器不暴露 value_type :(
    • @Johannes:我不知道为什么,你知道原因吗?
    • @Matthieu,我不知道。但也许他们可以支持“多态”迭代器。可以像output_iterator(cout) 这样创建流输出迭代器,然后可以创建*it++ = "value:"; *it++ = 42;
    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2011-06-30
    相关资源
    最近更新 更多