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);
}