Algorithm庫常用函數總結

Algorithm庫常用函數總結

可以去cplusplus官方網站查詢,地址http://www.cplusplus.com/reference/algorithm/

☁️algorithm是C++中Stl的標準模板庫,<algorithm>專門設計用於元素範圍範圍是可以通過迭代器或指針(例如數組或某些STL容器的實例)訪問的任何對象序列。但是請注意,算法通過迭代器直接對這些值進行操作,不以任何方式影響任何可能的容器的結構(它從不影響容器的大小或存儲分配)。

Functions in <algorithm>所有函數

🔽不想看可以跳過這一段列表,這裏介紹Algorithm的所有操作,每個函數都有一個鏈接,點擊即可到官網查看🔽

向下傳送門⬅️

Non-modifying sequence operations:

  • all_of

    Test condition on all elements in range (function template )

  • any_of

    Test if any element in range fulfills condition (function template )

  • none_of

    Test if no elements fulfill condition (function template )

  • for_each

    Apply function to range (function template )

  • find

    Find value in range (function template )

  • find_if

    Find element in range (function template )

  • find_if_not

    Find element in range (negative condition) (function template )

  • find_end

    Find last subsequence in range (function template )

  • find_first_of

    Find element from set in range (function template )

  • adjacent_find

    Find equal adjacent elements in range (function template )

  • count

    Count appearances of value in range (function template )

  • count_if

    Return number of elements in range satisfying condition (function template )

  • mismatch

    Return first position where two ranges differ (function template )

  • equal

    Test whether the elements in two ranges are equal (function template )

  • is_permutation

    Test whether range is permutation of another (function template )

  • search

    Search range for subsequence (function template )

  • search_n

    Search range for elements (function template )

Modifying sequence operations:

  • copy

    Copy range of elements (function template )

  • copy_n

    Copy elements (function template )

  • copy_if

    Copy certain elements of range (function template )

  • copy_backward

    Copy range of elements backward (function template )

  • move

    Move range of elements (function template )

  • move_backward

    Move range of elements backward (function template )

  • swap

    Exchange values of two objects (function template )

  • swap_ranges

    Exchange values of two ranges (function template )

  • iter_swap

    Exchange values of objects pointed to by two iterators (function template )

  • transform

    Transform range (function template )

  • replace

    Replace value in range (function template )

  • replace_if

    Replace values in range (function template )

  • replace_copy

    Copy range replacing value (function template )

  • replace_copy_if

    Copy range replacing value (function template )

  • fill

    Fill range with value (function template )

  • fill_n

    Fill sequence with value (function template )

  • generate

    Generate values for range with function (function template )

  • generate_n

    Generate values for sequence with function (function template )

  • remove

    Remove value from range (function template )

  • remove_if

    Remove elements from range (function template )

  • remove_copy

    Copy range removing value (function template )

  • remove_copy_if

    Copy range removing values (function template )

  • unique

    Remove consecutive duplicates in range (function template )

  • unique_copy

    Copy range removing duplicates (function template )

  • reverse

    Reverse range (function template )

  • reverse_copy

    Copy range reversed (function template )

  • rotate

    Rotate left the elements in range (function template )

  • rotate_copy

    Copy range rotated left (function template )

  • random_shuffle

    Randomly rearrange elements in range (function template )

  • shuffle

    Randomly rearrange elements in range using generator (function template )

Partitions:

Sorting:

  • sort

    Sort elements in range (function template )

  • stable_sort

    Sort elements preserving order of equivalents (function template )

  • partial_sort

    Partially sort elements in range (function template )

  • partial_sort_copy

    Copy and partially sort range (function template )

  • is_sorted

    Check whether range is sorted (function template )

  • is_sorted_until

    Find first unsorted element in range (function template )

  • nth_element

    Sort element in range (function template )

Binary search (operating on partitioned/sorted ranges):

  • lower_bound

    Return iterator to lower bound (function template )

  • upper_bound

    Return iterator to upper bound (function template )

  • equal_range

    Get subrange of equal elements (function template )

  • binary_search

    Test if value exists in sorted sequence (function template )

Merge (operating on sorted ranges):

  • merge

    Merge sorted ranges (function template )

  • inplace_merge

    Merge consecutive sorted ranges (function template )

  • includes

    Test whether sorted range includes another sorted range (function template )

  • set_union

    Union of two sorted ranges (function template )

  • set_intersection

    Intersection of two sorted ranges (function template )

  • set_difference

    Difference of two sorted ranges (function template )

  • set_symmetric_difference

    Symmetric difference of two sorted ranges (function template )

Heap:

  • push_heap

    Push element into heap range (function template )

  • pop_heap

    Pop element from heap range (function template )

  • make_heap

    Make heap from range (function template )

  • sort_heap

    Sort elements of heap (function template )

  • is_heap

    Test if range is heap (function template )

  • is_heap_until

    Find first element not in heap order (function template )

Min/max:

  • min

    Return the smallest (function template )

  • max

    Return the largest (function template )

  • minmax

    Return smallest and largest elements (function template )

  • min_element

    Return smallest element in range (function template )

  • max_element

    Return largest element in range (function template )

  • minmax_element

    Return smallest and largest elements in range (function template )

Other:

常用的函數

注意:給大家提供一個在線編譯器。叫做C++ Shell。此編譯器是cplusplus官網配套協作的編譯器,方便大家看完文檔寫代碼,給大家鏈接http://cpp.sh/很好用

1、max()、min()、abs()比較數字

這個在math頭文件也可以,浮點型的絕對值要用math的fabs

#include <iostream>
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 <iostream>     // std::cout
#include <algorithm>    // std::min_element, std::max_element

bool myfn(int i, int j) { return i<j; }

struct myclass {
  bool operator() (int i,int j) { return i<j; }
} myobj;

int main () {
  int myints[] = {3,7,2,5,6,4,9};

  // using default comparison:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7) << '\n';

  // using function myfn as comp:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myfn) << '\n';

  // using object myobj as comp:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myobj) << '\n';

  return 0;
}

運行結果

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::vector<int>v;
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 <iostream>
#include <algorithm>
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 <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<int>array;//動態數組
    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函數

快速排序,時間超短!
實例:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector<int> sortv; //動態數組
    for (int i = 0; i < 5; i++)
    {
        int t;
        cin >> t;
        sortv.push_back(t);
    }
    sort(sortv.begin(), sortv.end());
    for (int i = 0; i < 5; i++)
    {
        cout << sortv[i] << endl;
    }
    //數組
    int sortnums[6];
    for (int i = 0; i < 5; i++)
        cin >> sortnums[i];
    sort(sortnums, sortnums + 5);
    for (int i = 0; i < 5; i++)
        cout << sortnums[i] << endl;
    //此sort是升序排序
    return 0;
}

運行結果:

1 5 4 3 8
1
3
4
5
8
1 5 6 4 8
1
4
5
6
8

怎麼把sort函數改成降序呢?
在命名空間下方添加一個函數——cmp(名字任意)

bool cmp(int a, int b)
{
    return a > b;
}

sort函數改成這樣

sort(v.begin(), v.end(), cmp);

sort(sortv.begin(), sortv.end());
for (int i = 0; i < 5; i++)
{
cout << sortv[i] << endl;
}
//數組
int sortnums[6];
for (int i = 0; i < 5; i++)
cin >> sortnums[i];
sort(sortnums, sortnums + 5);
for (int i = 0; i < 5; i++)
cout << sortnums[i] << endl;
//此sort是升序排序
return 0;
}


運行結果:

1 5 4 3 8
1
3
4
5
8
1 5 6 4 8
1
4
5
6
8


怎麼把sort函數改成降序呢?
在命名空間下方添加一個函數——cmp(名字任意)

```cpp
bool cmp(int a, int b)
{
    return a > b;
}

sort函數改成這樣

sort(v.begin(), v.end(), cmp);

就可以了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章