views:

100

answers:

1
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;
}

I have this function splits an image up into frames and stores them into a container of images. How would I modify it to take an iterator instead of a container, and insert the elements at that point?

+3  A: 

Use 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;
}

Then call it like

ExtractFrames(std::back_inserter(container), ...);
Johannes Schaub - litb
Every time I see an answer like this I learn how little I know about STL. :(
Matteo Italia
I did this: ExtractFrames(std::back_inserter(surface_vec), c_width, c_height, 16, 6, true); -------- And then I get the following errors: "error C2182: 'v' : illegal use of type 'void'", "error C2440: 'initializing' : cannot convert from 'value_type' to 'int'", and some others. surface_vec is an std::vector<BlitSurface>
PigBen
@user um my bad. output-iterators don't expose value_type :(
Johannes Schaub - litb
@Johannes: I do wonder why, do you happen to know the reason ?
Matthieu M.
@Johannes: Thanks, it helped a lot. But I don't understand your comment -- // "BlitSurface()" sets other members to zero. -- Wouldn't it just call my default constructor? And wouldn't this "BlitSurface bs = BlitSurface()" end up calling my default constructor and passing the reference to my copy constructor?
PigBen
@Matthieu, i've no idea. But maybe so they could support "polymorphic" iterators. A stream-output iterator could be created like `output_iterator(cout)` and one could then do `*it++ = "value:"; *it++ = 42;`.
Johannes Schaub - litb