Reversing 2nd order deep std::vector

Reversing 2nd order deep std::vector

Post by Jack » Sun, 02 May 2010 17:44:07


Dear all,

std::vector<x> finalvector;
std::vector<x> x1;
std::vector<std::vector<x>> x2;


for (...)
{
for (...) {
x1.push_back(data);
}
x2.push_back(x1);
}

std::vector<std::vector<x>>::reverse_iterator it;
for (it = x2.rbegin(); it != x2.end(); it++)
{
finalvector.push_back(**it); <<<<<<<<<<<<< compilation error
}

I'd like to reverse a grid in a y-axis while keeping the x-axis components
intact.

For example
1 2 3 4 5 6 7 8
a b c d e f g h

to

a b c d e f g h
1 2 3 4 5 6 7 8

Is it the correct way of doing it?
Thanks in advance
Jack
 
 
 

Reversing 2nd order deep std::vector

Post by Jack » Sun, 02 May 2010 17:58:04

> for (it = x2.rbegin(); it != x2.end(); it++)

Sorry, typo x2.rend(), still doesn't compile
Thanks

 
 
 

Reversing 2nd order deep std::vector

Post by David Lown » Sun, 02 May 2010 21:40:47

>std::vector<x> finalvector;

finalvector should be the same type as x2, i.e.:

std::vector<std::vector<x>> finalvector;

and then use:

finalvector.push_back( *it );

However, an easier solution is to use:

#include <algorithm>

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

Dave
 
 
 

Reversing 2nd order deep std::vector

Post by Jack » Sun, 02 May 2010 21:49:38


Thanks David,
I'll give it a try!
Jack
 
 
 

Reversing 2nd order deep std::vector

Post by Stephan T. » Mon, 03 May 2010 12:33:17

You should point out that std::reverse() will be significantly more
efficient. It swaps instead of copying.

In general, it's a good idea to use Standard Library algorithms whenever
possible. Their designers and implementers worked hard to make them as
efficient as possible. Using Standard Library containers is simply the first
step.

Stephan T. Lavavej
Visual C++ Libraries Developer