自学内容网 自学内容网

STL——常用排序算法

 1.sort()

 

void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int> v1;
v1.push_back(10);
v1.push_back(20);
v1.push_back(40);
v1.push_back(30);
v1.push_back(20);
v1.push_back(40);
v1.push_back(50);
sort(v1.begin(), v1.end(), greater<int>());//用内建函数模板实现降序
for_each(v1.begin(), v1.end(), MyPrint);
cout << endl;
}

2.random_shuffle()//随机打乱顺序

void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int> v1;
srand((unsigned int)time(NULL));//随机数种子
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
for_each(v1.begin(), v1.end(), MyPrint);
cout << endl;
cout << "随机打乱顺序后" << endl;
random_shuffle(v1.begin(), v1.end());//随机打乱顺序
for_each(v1.begin(), v1.end(), MyPrint);
cout << endl;
}

 3.merge()//归并

 

void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int> v1;
vector<int> v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 1);
}
vector<int> v3;
v3.resize(v1.size() + v2.size());//归并前必须先开辟空间
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());//必须是有序且升序
for_each(v3.begin(), v3.end(), MyPrint);
cout << endl;
}

4.reverse()//反转

void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int> v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
cout << "反转前:" << endl;
for_each(v1.begin(), v1.end(), MyPrint);
cout << endl;
reverse(v1.begin(), v1.end());//实现反转
cout << "反转后:" << endl;
for_each(v1.begin(), v1.end(), MyPrint);
cout << endl;
}


原文地址:https://blog.csdn.net/weixin_74207910/article/details/140658904

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!