C++ STL變序型算法 旋轉元素rotate 使用方法

在這裏插入圖片描述

將[First, Last]區間中的元素旋轉,旋轉後_Mid成爲新的第一元素

複雜度:線性,字最多進行numElems次交換

使用例子:

template<typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
	for (int i = first; i <= last; ++i)
	{
		coll.insert(coll.end(), i);
	}
}
template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
	cout << optcstr;
	for (auto elem : coll)
	{
		cout << elem << ' ';
	}
	cout << endl;

}
int main()
{


	vector<int>a;
	INSERT_ELEMENTS(a, 1, 9);
	PRINT_ELEMENTS(a, "a: ");
	rotate(a.begin(), a.begin()+1,a.end());
	PRINT_ELEMENTS(a, "one left: ");

	rotate(a.begin(), a.end() - 2, a.end());
	PRINT_ELEMENTS(a, "two right: ");
	rotate(a.begin(),find(a.begin(),a.end(),4),a.end());
	PRINT_ELEMENTS(a, "4 first: ");
	cout << endl;
}

在這裏插入圖片描述

發佈了314 篇原創文章 · 獲贊 231 · 訪問量 8959
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章