C++ algorithm庫

一、基礎算法

C++ algorithm庫提供了各種基礎算法,包括排序、查找、修改和遍歷等。下面以排序算法為例進行闡述。

1、排序算法

C++ algorithm庫提供了多種排序算法,包括快排、歸併排序、堆排序等。以下為快排算法示例:

#include 
#include 
#include 
using namespace std;

int partition(vector &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 &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 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 
#include 
#include 
using namespace std;

int main()
{
    vector 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 
#include 
#include 
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 
#include 
#include 
using namespace std;

void print(int i)
{
    cout << i << " ";
}

int main()
{
    vector 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 
#include 
#include 
using namespace std;

bool compareByName(const Person &a, const Person &b)
{
    return a.name < b.name;
}

int main()
{
    vector 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

原創文章,作者:DQGNZ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/332139.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
DQGNZ的頭像DQGNZ
上一篇 2025-01-21 17:30
下一篇 2025-01-21 17:30

發表回復

登錄後才能評論