Rotation of a vector (array)

I am trying to rotate a vector of elements in C ++. I mean, I have a vector<point> I want the last element to become the first.

Example:

[1,2,3] become [3,1,2], then [2,3,1]

For this, I tried to do the following:

 //Add the last element at index 0 ObjectToRotate.insert(0, ObjectToRotate.at(ObjectToRotate.size()-1)); //Remove Last element ObjectToRotate.erase(ObjectToRotate.size()-1); 

but I get this error:

 Error 6 error C2664: 'std::_Vector_iterator<_Myvec> std::vector<_Ty>::insert<cv::Point_<_Tp>&>(std::_Vector_const_iterator<_Myvec>,_Valty)' : cannot convert parameter 1 from 'int' to 'std::_Vector_const_iterator<_Myvec>' 

How can I solve it?

thanks

+6
source share
5 answers

The std::rotate algorithm exists in the standard library:

 std::rotate(ObjectToRotate.begin(), ObjectToRotate.end()-1, // this will be the new first element ObjectToRotate.end()); 
+13
source

The recommendations for using std::rotate , of course, completely correct; using an existing function is always the preferred solution when available. However, it’s worth pointing out why your solution doesn’t work. Containers in the standard library, such as std::vector , occupy position information in the form of iterators, not indexes. The idiomatic way of writing your operation would be:

 v.insert( v.begin(), v.back() ); v.erase( std::prev( v.end() ) ); 

(If you don't have C ++ 11, it's pretty simple to write your version of prev . Or, in the case of vector you can just write v.end() - 1 )

+6
source

The insert and erase are iterators, not indexes:

 ObjectToRotate.insert(ObjectToRotate.begin(), ObjectToRotate.back()); ObjectToRotate.pop_back(); // or erase(ObjectToRotate.end()-1), if you prefer 

But it may be more efficient to remove the last item (after copying) to avoid the possibility of redistribution:

 auto back = ObjectToRotate.back(); ObjectToRotate.pop_back(); ObjectToRotate.insert(ObjectToRotate.begin(), back); 

or use std::rotate :

 std::rotate(ObjectToRotate.begin(), ObjectToRotate.end()-1, ObjectToRotate.end()); 

If you do this a lot, then deque may be the best container choice, as it allows you to efficiently insert and remove from both ends. But, if speed is important, make sure you measure and verify that it is truly an improvement; if the sequence is not very long, then the overhead from a more complex memory layout can make deque slower.

+3
source

to create [1,2,3] - [2.3.1] here is the code

 vector<int> Solution::rotateArray(vector<int> &A, int B) { vector<int> ret; for (int i = 0; i < A.size(); i++) { ret.push_back(A[(i + B) % A.size()]); } return ret; 

}

here A is [1,2,3] and B is 1 to move 1 position

+1
source

Source: https://habr.com/ru/post/919747/


All Articles