Boost logo

Boost :

From: Hervé Brönnimann (hervebronnimann_at_[hidden])
Date: 2007-12-29 12:25:58


Phil: Pardon my ignorance about ptr_vector, but you may be thinking
about the wrong STL algorithm: try rotate instead of copy:

void shift(int start, int end) {
    std::rotate(start, start+1, end+1);
    // brings v[start] to v[end] and shifts everyone else by one
position down
    LargeThing *tmp = v[end];
    pop_back();
    // vector is now in a stable state, if delete throws (gasp! hope
not!) or if new throws, it only contains valid pointers
    delete tmp;
    v.push_back(new LargeThing);
}

Assuming constructor does not throw, your vector will have one less
element in the presence of exception thrown by the ctor, and
otherwise the extra cost is simply decrementing and re-incrementing
the vector size member, no big deal compared to a LargeThing ctor.

Small note about the interface: I would have made end be one-past-
the-position, in STL fashion. HTH,
--HB

On Dec 29, 2007, at 10:38 AM, Phil Endecott wrote:
> Dear Experts,
>
> I have some code which currently uses a std::vector of pointers, and
> I'm investigating whether I can make it more concise, exception-safe,
> or otherwise better using a ptr_vector. But I can't see a good way to
> replace the following code, which shifts part of the vector by one
> place, deleting one pointee and creating a new one at the other end:
>
> struct LargeThing { .... };
> std::vector<LargeThing*> v;
>
> void shift(int start, int end) {
> delete v[start];
> for (int i=start; i<end; ++i) { // or use a std::algorithm
> v[i]=v[i+1];
> }
> v[end] = new LargeThing;
> }


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk