C++algorithm库函数常用函数


常用函数

1. max()、min()、abs()比较数字

这个在math头文件也可以,浮点型的绝对值要用math的fabs

#include 
using namespace std;
int main()
{
    int a, b;
    cin >> a >> b;
    cout << max(a, b) << endl;
    cout << min(a, b) << endl;
    cout << abs(a - b) << endl;
    return 0;
}

2. *max_element()、*min_element()比较容器(数组、字符串等)

上面的max、min函数只能比较数字,如果比较数组等容器怎么办,就用*…_element()方法

// min_element/max_element example
#include      // std::cout
#include     // std::min_element, std::max_element

bool myfn(int i, int j) { return i

运行结果

The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9

注意,min_element和max_element要加星号*,因为iterator迭代器,就加上就行了
下面是比较动态数组伪代码

std::vectorv;
v.push_back(10);
v.push_back(20);
v.push_back(30);
std::cout << *max_element(v.begin(), v.end()) << std::endl;

3. swap()交换值

这个一般不用algorithm库也可以实现swap函数,但还是比较常用

#include 
#include 
using namespace std;
int main()
{
    int a, b;
	swap(a, b);
    cout << a << " " << b << endl;
    int nums[4] = {0, 1, 2, 3};
    swap(nums[0], nums[3]);
    for (int i = 0; i < 3; i++)
        cout << nums[i] << " ";
    cout << endl;
    return 0;
}

4. reverse()翻转容器

reverse()函数可以将一个容器直接翻转,例如数组、动态数组和字符串等

#include 
#include 
#include 
#include 
using namespace std;
int main()
{
    vectorarray;//动态数组
    for (int i = 0; i < 5; i++)
    {
        int t;
        cin >> t;
        array.push_back(t);
    }
    reverse(array.begin(), array.end());
    for (int i = 0; i < array.size(); i++)
        cout << array[i] << " ";
    cout << endl;
    cout << "--------" << endl;
    string str = "hello world";//字符串
    reverse(str.begin(), str.end());
    cout << str << endl;
    cout << "--------" << endl;
    int arr1[101]; //数组
    for (int i = 0; i < 5; i++)
    {
        cin >> arr1[i];
    }
    reverse(arr1, arr1 + 5);
    for (int i = 0; i < 5; i++)
    {
        cout << arr1[i] << " ";
    }
    cout << endl;
    return 0;
}

输出结果:

1 2 3 4 5
5 4 3 2 1
--------
dlrow olleh
--------
5 2 6 4 5
5 4 6 2 5

5. 快速排序——sort函数

升序:sort(begin,end,less());
降序:sort(begin,end,greater());

升序排列

#include
#include
using namespace std;

int main() {
	int n;
	int a[200];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	sort(a, a + n,less());
	for (int i = 0; i < n; i++) {
		cout << a[i] << " ";
	}

	return 0;
}

降序排列

#include
#include
using namespace std;

int main() {
	int n;
	int a[200];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	sort(a, a + n,greater());
	for (int i = 0; i < n; i++) {
		cout << a[i] << " ";
	}

	return 0;
}