Move first element of Vector to last element

故事扮演 提交于 2019-12-11 04:14:13

问题


I want to move first element of vector to the end of vector.

v = {1,2,3,4} after this should be like this

v= {2,3,4,1}

my compiler version is gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1)

I know in Vc11 we can use std::move to move element. but how can I do this in above version of compiler?


回答1:


There's a std::rotate algorithm in the standard library:

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



回答2:


You should consider using std::rotate or if you want it the ugly way: Create a function that safes the last and the first element in local variables, create a new local vector, but the last element as first in the vector. Put begin+1 till end-1 in the vector and then the first element.




回答3:


As noted in the comments, std::rotate is one possible way:

std::rotate( v.begin(), v.begin() + 1, v.end() );


来源:https://stackoverflow.com/questions/26346056/move-first-element-of-vector-to-last-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!