Discussion:
Reversing 2nd order deep std::vector
(too old to reply)
Jack
2010-05-01 08:44:07 UTC
Permalink
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
Jack
2010-05-01 08:58:04 UTC
Permalink
Post by Jack
for (it = x2.rbegin(); it != x2.end(); it++)
Sorry, typo x2.rend(), still doesn't compile
Thanks
David Lowndes
2010-05-01 12:40:47 UTC
Permalink
Post by Jack
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
Jack
2010-05-01 12:49:38 UTC
Permalink
Thanks David,
I'll give it a try!
Jack
Stephan T. Lavavej [MSFT]
2010-05-02 03:33:17 UTC
Permalink
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
Post by David Lowndes
Post by Jack
std::vector<x> finalvector;
std::vector<std::vector<x>> finalvector;
finalvector.push_back( *it );
#include <algorithm>
std::reverse( x2.begin(), x2.end() );
Dave
Loading...