1. 程式人生 > >STL之修改集合裡邊元素的順序

STL之修改集合裡邊元素的順序

這裡我們使用rotate函式。具體函式作用可見程式碼輸出。

//#include "learn.h"
#include<stdio.h>
#include<iostream>
#include<vector>
#include<map>
#include<list>
#include<string>
#include<iterator>
#include<stdlib.h>
#include<algorithm>
using namespace std;
template<typename datatype>
void ChangeOrder(vector<datatype> &V, int pos)//模板方法
{
	for (int i = 0; i < V.size(); i++)
		cout << V[i] << " ";
	cout << endl;
	if (!(pos >= 0))
		return;
	if (pos >= V.size())
		return;
	rotate(V.begin(), V.begin() + pos, V.end());
	for (int i = 0; i < V.size(); i++)
		cout << V[i] << " ";
	cout << endl;
	rotate(V.begin(), V.begin() + 1, V.begin() + (V.size() - pos));
	for (int i = 0; i < V.size(); i++)
		cout << V[i] << " ";
	cout << endl;
}
void changeorder(vector<int> &V,int pos)
{
	for (int i = 0; i < V.size(); i++)
		cout << V[i] <<" ";
	cout << endl;
	if (!(pos >= 0))
		return;
	if (pos >= V.size())
		return;
	rotate(V.begin(),V.begin()+pos,V.end());
	for (int i = 0; i < V.size(); i++)
		cout << V[i]<<" ";
	cout << endl;
	rotate(V.begin(), V.begin() + 1, V.begin() + (V.size() - pos));
	for (int i = 0; i < V.size(); i++)
		cout << V[i] <<" ";
	cout << endl;
}

int main()
{
	int array[10] = { 0,1,2,3,4,5,6,7,8,9 };
	vector<int> V(array, array + 10);
	//changeorder(V, 5);
	ChangeOrder(V, 5);
}

 

執行結果為

 

 

假設原集合順序為  A~B~C(~為AB和BC之間的元素)   其中rotate(A,B,C)函式執行成功之後,集合元素順序為B~CA~,即相當於把B即後邊的元素換到A前邊來。