C++ algorithm库

发布时间:2023-05-22

一、基础算法

C++ algorithm库提供了各种基础算法,包括排序、查找、修改和遍历等。下面以排序算法为例进行阐述。

1、排序算法

C++ algorithm库提供了多种排序算法,包括快排、归并排序、堆排序等。以下为快排算法示例:

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int partition(vector<int> &arr, int low, int high)
{
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j <= high; j++)
    {
        if (arr[j] <= pivot)
        {
            i++;
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return i + 1;
}
void quicksort(vector<int> &arr, int low, int high)
{
    if (low < high)
    {
        int pi = partition(arr, low, high);
        quicksort(arr, low, pi - 1);
        quicksort(arr, pi + 1, high);
    }
}
int main()
{
    vector<int> arr = {3, 7, 1, 4, 2, 8, 5, 6};
    quicksort(arr, 0, arr.size() - 1);
    for (auto a : arr)
    {
        cout << a << " ";
    }
    return 0;
}
//输出: 1 2 3 4 5 6 7 8

二、数字操作

除了基础算法,C++ algorithm库还提供了数组操作、随机数生成、数学函数等数字操作相关功能。下面以求最小值为例进行阐述。

1、求最小值

C++ algorithm库提供了min_element函数,可以方便地求出数组中的最小值。以下为示例:

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
    vector<int> arr = {3, 7, 1, 4, 2, 8, 5, 6};
    auto it = min_element(arr.begin(), arr.end());
    cout << "The minimum element is " << *it << endl;
    return 0;
}
//输出: The minimum element is 1

三、字符串操作

C++ algorithm库还提供了字符串操作相关的算法,包括字符串查找、替换和拼接等。下面以字符串查找为例进行阐述。

1、字符串查找

C++ algorithm库提供了find函数,可以方便地在字符串中查找指定字符。以下为示例:

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str = "hello world";
    auto it = find(str.begin(), str.end(), 'w');
    if (it != str.end())
    {
        cout << "Found 'w' at position " << it - str.begin() << endl;
    }
    else
    {
        cout << "Not found 'w'" << endl;
    }
    return 0;
}
//输出: Found 'w' at position 6

四、迭代器操作

C++ algorithm库还提供了各种迭代器操作,包括遍历和转换等。下面以遍历为例进行阐述。

1、迭代器遍历

C++ algorithm库提供了for_each函数,可以方便地遍历容器。以下为示例:

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void print(int i)
{
    cout << i << " ";
}
int main()
{
    vector<int> arr = {3, 7, 1, 4, 2, 8, 5, 6};
    for_each(arr.begin(), arr.end(), print);
    return 0;
}
//输出: 3 7 1 4 2 8 5 6

五、结构体操作

C++ algorithm库甚至还提供了结构体相关的操作,包括按照指定字段排序等。以下以按照姓名排序为例进行阐述。

1、按照姓名排序

假设有如下结构体:

struct Person
{
    string name;
    int age;
};

C++ algorithm库提供了sort函数,可以方便地按照指定字段排序。以下为示例:

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool compareByName(const Person &a, const Person &b)
{
    return a.name < b.name;
}
int main()
{
    vector<Person> people = {{"Dan", 20}, {"Alice", 18}, {"Bob", 22}};
    sort(people.begin(), people.end(), compareByName);
    for (auto p : people)
    {
        cout << p.name << " " << p.age << endl;
    }
    return 0;
}
//输出:
//Alice 18
//Bob 22
//Dan 20