STL之排序演算法
阿新 • • 發佈:2018-11-19
1.merge()
以下是排序和通用演算法:提供元素排序策略
merge: 合併兩個有序序列,存放到另一個序列。
例如:
vecIntA,vecIntB,vecIntC是用vector宣告的容器,vecIntA已包含1,3,5,7,9元素,vecIntB已包含2,4,6,8元素
vecIntC.resize(9); //擴大容量
merge(vecIntA.begin(),vecIntA.end(),vecIntB.begin(),vecIntB.end(),vecIntC.begin());
此時vecIntC就存放了按順序的1,2,3,4,5,6,7,8,9九個元素
2.sort()
sort: 以預設升序的方式重新排列指定範圍內的元素。若要改排序規則,可以輸入比較函式。
//學生類
Class CStudent:
{
public:
CStudent(int iID, string strName)
{
m_iID=iID;
m_strName=strName;
}
public:
int m_iID;
string m_strName;
}
//學號比較函式
bool Compare(const CStudent &stuA,const CStudent &stuB)
{
return (stuA.m_iID<strB.m_iID);
}
void main()
{
vector<CStudent> vecStu;
vecStu.push_back(CStudent(2,"老二"));
vecStu.push_back(CStudent(1,"老大"));
vecStu.push_back(CStudent(3,"老三"));
vecStu.push_back(CStudent(4,"老四"));
sort(vecStu.begin(),vecStu.end(),Compare);
//此時,vecStu容器包含了按順序的"老大物件","老二物件","老三物件","老四物件"
}
3.random_shuffle()
random_shuffle: 對指定範圍內的元素隨機調整次序。
srand(time(0)); //設定隨機種子
vector<int> vecInt;
vecInt.push_back(1);
vecInt.push_back(3);
vecInt.push_back(5);
vecInt.push_back(7);
vecInt.push_back(9);
string str("itcastitcast ");
random_shuffle(vecInt.begin(), vecInt.end()); //隨機排序,結果比如:9,7,1,5,3
random_shuffle(str.begin(), str.end()); //隨機排序,結果比如:" itstcasticat "
reverse()
vector<int> vecInt;
vecInt.push_back(1);
vecInt.push_back(3);
vecInt.push_back(5);
vecInt.push_back(7);
vecInt.push_back(9);
reverse(vecInt.begin(), vecInt.end()); //{9,7,5,3,1}
綜合程式碼
void main_merge()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
vector<int> v2;
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
vector<int> v3;
v3.resize(v1.size() + v2.size() );
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin() );
printV(v3);
}
class Student
{
public:
Student(string name, int id)
{
m_name = name;
m_id = id;
}
void printT()
{
cout << "name: " << m_name << " id " << m_id << endl;
}
public:
string m_name;
int m_id;
};
bool CompareS(Student &s1, Student &s2)
{
return (s1.m_id < s2.m_id);
}
void main_sort()
{
Student s1("老大", 1);
Student s2("老二", 2);
Student s3("老三", 3);
Student s4("老四", 4);
vector<Student> v1;
v1.push_back(s4);
v1.push_back(s1);
v1.push_back(s3);
v1.push_back(s2);
for (vector<Student>::iterator it=v1.begin(); it!=v1.end(); it++)
{
it->printT() ;
}
//sort 根據自定義函式物件 進行自定義資料型別的排序
//替換 演算法的統一性 (實現的演算法和資料型別的分離) ===>技術手段函式物件
sort(v1.begin(), v1.end(), CompareS );
for (vector<Student>::iterator it=v1.begin(); it!=v1.end(); it++)
{
it->printT() ;
}
}
void main_random_shuffle()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v1.push_back(7);
random_shuffle(v1.begin(), v1.end());
printV(v1);
string str = "abcdefg";
random_shuffle(str.begin(), str.end());
cout << "str: " << str << endl;
}
void main_reverse()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v1.push_back(7);
reverse(v1.begin(), v1.end());
printV(v1);
}