1.sort 函数
sort 函数是 algorithm 中的排序函数,相较于 C stdlib 中的 qsort 函数,用法更简单,也更广泛,同时内部实现也要更复杂。
对数组使用 sort 函数:
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
int arr [10] = { 2,4,1,6,7,5,8,10,3,9 };
cout << "排序前的数组:";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
sort (arr , arr + 10);
cout << "排序后的数组:";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
system ("pause");
return 0;
}
注意:这里的参数是数组的地址。
对容器 vector 使用 sort 函数:
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
vector<int> arr = { 2,4,1,6,7,5,8,10,3,9 };
cout << "排序前的数组:";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
sort (arr.begin () , arr.end ());
cout << "排序后的数组:";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
system ("pause");
return 0;
}
2. reverse 函数
reverse 函数是 algorithm 中的反转函数,常适用于字符串,但不仅仅可以对字符串使用。
对 string 使用 reverse 函数:
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
string s = "Hello world";
cout << "反转前的字符串:";
cout << s << endl;
reverse (s.begin () , s.end ());
cout << "反转后的字符串:";
cout << s << endl;
system ("pause");
return 0;
}
3. max & min 函数
max & min 函数是用来返回两变量之间较大(小)者的函数。
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
int a , b;
a = 1;
b = 10;
cout << "a:" << a << "," << "b:" << b << endl;
cout << "较大者:" << max (a , b) << endl;
cout << "较小者:" << min (a , b) << endl;
system ("pause");
return 0;
}
4. max_element & min_element 函数
该函数用于获取数组或容器中最大(小)的元素。
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
vector<int> arr = { 1,2,3,4,5,6,7,8,9,0 };
cout << "数组:";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
cout << "最大者:";
cout << *max_element (arr.begin () , arr.end ()) << endl;
cout << "最小者:";
cout << *min_element (arr.begin () , arr.end ()) << endl;
system ("pause");
return 0;
}
注意:该函数的返回值是元素的地址(对于容器,返回迭代器)。
5. binary_search 函数
函数一共三个参数,第一二个参数参照 sort 的参数,第三个参数是需要寻找的 key。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main () {
vector<int> haystack{ 1, 3, 4, 5, 9 };
vector<int> needles{ 1, 2, 3 };
for (const auto needle : needles) {
cout << "正在搜索 " << needle << '\n';
if (binary_search (haystack.begin () , haystack.end () , needle))
cout << "找到了 " << needle << '\n';
else
cout << "没找到!\n";
}
system ("pause");
return 0;
}