Recommendation for moving / shifting vector members?
Oleg Endo
oleg.endo@t-online.de
Thu Jul 17 21:18:00 GMT 2014
On Thu, 2014-07-17 at 13:29 -0700, Linda A. Walsh wrote:
> I note that the 'shift' function isn't implemented for the vector
> template as for valarray.
>
> But I have a case where I want to use the vector extensibility to hold
> a variable number of items up to some max (something valarray can't do
> w/no capacity()/reserve() functionality).
>
> Is there a "memmove" type function or a "shift" type function in the C++
> library to work on the valid members of a vector.
>
> Ex: Elements 0..N-1 => 1->N (nothing extending into the capacity, but just
> moving the "valid" members).
>
> I can think of multiple ways to do this in different containers
> I.e. manually store indexes into a valarray to represent the
> "valid" bounds of the sub members, or using some other container,
> but was wondering if the C++ library had some way of doing it.
The generic version is probably std::rotate
http://en.cppreference.com/w/cpp/algorithm/rotate
> I'm not sure if memmove on the members is supported or not?
> Are they supposed to be contiguous in memory and memmove is
> 'fine' -- and I'm overthinking this, or is there better
> solution?
The elements stored in a vector are in contiguous memory. That's one
key property of the container. See also the description in
http://en.cppreference.com/w/cpp/container/vector
> It seems like moving the backing store of the
> container (i.e. memmove), could potentially break the object
> paradigm and be unsupported, at least in some cases (if in any?)
>
> Thanks & it sure would have been nice if 'shift' worked on vectors
> as well as valarrays... (sigh)...
You could write your own rotate function (or specialize std::rotate) for
certain types of vector elements. In order to use memmove, elements
must be trivial ( http://en.cppreference.com/w/cpp/types/is_trivial )
The specialization then can be enabled for appropriate types via
std::enable_if and friends.
If the std::vector class itself is a custom made specialization, things
could be a bit difficult to handle in a generic way from outside the std
lib implementation.
Cheers,
Oleg
More information about the Libstdc++
mailing list