stl vector reverse method

V

Vasileios Zografos

Hi there I am using the STL vector and I was wondering, is there an
existing method for reversing the contents of one vector?

e.g. vector<int> v1 which has entries 1,2,3,4,5
and I want to end up with v1=5,4,3,2,1 or perhaps leave v1 intact and
generate a new vector v2=5,4,3,2,1

so, does the STL have something allready? or do I have to do it manualy?

Thanks
V.Z.
 
S

Sam Holden

Hi there I am using the STL vector and I was wondering, is there an
existing method for reversing the contents of one vector?

e.g. vector<int> v1 which has entries 1,2,3,4,5
and I want to end up with v1=5,4,3,2,1 or perhaps leave v1 intact and
generate a new vector v2=5,4,3,2,1

so, does the STL have something allready? or do I have to do it manualy?

std::reverse(v1.begin(), v1.end());

or:

std::vector<whatever> v2(v1.size());
std::reverse_copy(v1.begin(), v1.end(), v2.begin());

Surely you have a book with this stuff in it?

Or even: http://www.sgi.com/tech/stl/
 
V

Vasileios Zografos

Surely you have a book with this stuff in it?

Nope. But can you suggest one?

Thank you for the help.
V.Z.
 
M

Michiel Salters

std::reverse(v1.begin(), v1.end());

or:

std::vector<whatever> v2(v1.size());
std::reverse_copy(v1.begin(), v1.end(), v2.begin());

The latter can also be written as

std::vector< > v2( v1.rbegin(), v1.rend() );

which saves v1.size() default-initializations of whatevers (which might
be impossible, default ctors aren't mandatory)

Regards,
 
J

John Harrison

The latter can also be written as

std::vector< > v2( v1.rbegin(), v1.rend() );

which saves v1.size() default-initializations of whatevers (which might
be impossible, default ctors aren't mandatory)

Regards,

Default ctors are mandatory to be compliant with the STL.

john
 
R

Ron Natalie

John Harrison said:
Default ctors are mandatory to be compliant with the STL.

Default constructors are NOT mandatory. The requirement is that the contents
be copy constructable and assignable. The few functions that need to be able
to create "defaulted" objects take a parameter (defaulted to a default constructed
object) that is copied to these objects. If you provide a non-default constructed
object for these functions, your object does not need default constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,525
Members
44,997
Latest member
mileyka

Latest Threads

Top