Home > Blockchain >  C Reverse Array of std::vector of two elements
C Reverse Array of std::vector of two elements

Time:10-30

I would like to ask how can I fastly, without copying of elements reverse the array, that will always consists only from 2 std::vectors. The CGAL_Polyline is also a vector that contains points.

Currently I am doing reverse like this (works for now but I do not know if this is a correct way):

std::vector<CGAL_Polyline> m[2]; //array to reverse
std::vector<CGAL_Polyline> m_[2]{  m[1], m[0] };
m[0] = m_[0];
m[1] = m_[1];

this does not work, why?

std::vector<CGAL_Polyline> m[2]; //array to reverse
std::reverse(m.begin(), m.end());

Is there any other way to flip the order of two vectors? I do not need to reverse order of items in the vectors.

CodePudding user response:

Use std::swap:

std::vector<CGAL_Polyline> m[2];
...
std::swap(m[0], m[1]);

This will move the contents of the vectors without copying (C 11 and later. Before that it's allowed to copy).

If pre-C 11 (and if that's the case upgrade your compiler!) you can use std::vector::swap:

std::vector<CGAL_Polyline> m[2];
...
m[0].swap(m[1]);

Since it's guaranteed to be constant.

  •  Tags:  
  • c
  • Related