STL note (5) algorithm Algorithm

Source: Internet
Author: User

In STL, algorithms are a series of function templates. STL provides about 70 algorithms, which are composed of header files <algorithm>, <numeric>, and <functional>.

    • The header file <algorithm> is the largest one. Common functions include searching, sorting, modifying, removing, exchanging, and merging;
    • The header file <numeric> is small, mainly including function templates for number order operations;
    • The header file <functional> defines some class templates to declare function objects;

Classification of algorithms:

    • Algorithms can be divided into eight categories based on their functions: search, sorting, numerical calculation, comparison, set, container management, statistics, and operations.
    • Algorithms can be divided into four categories based on the impact on containers: uncorrected, corrected, sorted, and numerical calculation.

The non-correction algorithm does not modify elements in the container unless it is a read-only operation. Such as find (), count (), equal (), for_each (), and search. The details are as follows:

adjacent_find     #查找相同的相邻元素 反悔第一个元素的迭代器find              #查找元素 还有find系列查找函数find_first_offind_endfind_last_ofcount             #统计相同元素的个数count_ifmismatch          #返回 pair<第一个序列的迭代器,第二个序列的迭代器> 表明第一处不相符合的位置equal             #比较容器中的元素是否相同for_each          #常用,遍历序列并对序列中每个元素采用仿函数中定义的操作search            #返回迭代器,第一次出现序列2或者某元素的位置search_n          #前n次连续出现某元素或者符合条件的第一个位置
Correction Algorithm

The Correction Algorithm modifies the elements in the container and requires write operations. For example, copy (), remove (), reverse (), swap (), and unique. The details are as follows:

copy                #复制元素到目的容器copy_backward       #从后往前复制fill                #用某元素填充容器fill_ngenerate            #把仿函数产生的结果依次复制到容器中generate_npartition           #以仿函数为标准,把容器分成前后两部分,前半部分是能使仿函数返回真的元素,后半返回假stable_partitionrandom_shuffle      #对容器中的元素进行随机排列remove              #删除某一范围内的元素,注意:移除的元素被放到容器末尾,还是可以用迭代器遍历到,函数返回移除后容器的末尾remove_iferase               #擦除区间内所有的元素replace             #在规定区间内把某值换成新值replace_ifreplace_copy        #把区间内元素复制到目的地并且把其中某些元素替换成新值replace_copy_ifrotate              #把middle-end的元素放到first的位置上rotate_copyswap                #元素的交换swap_rangestransform           #把元素按照仿函数中内容转换unique              #保证相邻元素间没有相同的,可以加仿函数做为判断依据,返回最后一个位置的迭代器unique_copy

The sorting algorithm needs to move elements, so random access iterator radomaccessiterator must be used to specify the frontend, backend, and closed intervals of [begin, end, you can define a comparison function as needed for parameter input.

Sorting of Common Containers
    • Vector and deque, as well as arrays, support random access and can be sorted using algorithm;
    • The list container is a two-way linked list and does not support Random Access to the iterator. It has a built-in stable sorting method that uses the bottom-up Merge Sorting;
    • The bottom layer of MAP and set is a red-black tree, which itself is an ordered storage;

Common sorting functions
sort                    #对给定区间所有元素进行排序,用的是快排stable_sort             #稳定排序,保证值相等的元素排序后相对位置不变,用归并排序实现partial_sort            #部分排序,保证前n个值有序并且后面的值不在前n个值的范围内,但后面的值不保证有序,堆排序实现partial_sort_copy       #对给定区间复制并排序nth_element             #把第n个元素放到第n个位置上去,比他大的都在后,比他小的都在前,但各自都不保证有序is_sorted               #判断一个区间是否已经排好序partition               #使得符合某个条件的元素放在前面stable_partition        #相对稳定的使得符合某个条件的元素放在前面

Common comparison functions
less              #小于(缺省比较函数)greater           #大于equal_to          #等于less_equal        #小于等于greater_equal     #大于等于

Custom compare size

During use, you cannot directly write the name of the imitation function. Instead, you need to write its overloaded () function, such as less <int> (). Below are some of the less source code in STL:

template <class _Tp>struct less : public binary_function<_Tp,_Tp,bool>{  bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; }};

For basic data types and strings, you can use existing function templates in STL. For classes defined by yourself, you can write comparison functions or overload operators. Here, the overload <operator is equivalent to indirectly using the built-in less

Small Example
#include <iostream>#include <vector>#include <algorithm>using namespace std;class Test {public:    Test(int a):a(a){};    int a;    bool operator <(const Test &k) const {        return a < k.a;    }};int main(){    vector<Test> a;    a.push_back(Test(2));    a.push_back(Test(3));    a.push_back(Test(1));    vector<Test>::iterator iter;    sort(a.begin(), a.end());    for(iter = a.begin(); iter != a.end(); ++iter){        cout<< iter->a <<" ";    }  // 输出排序后:1 2 3}

Numeric calculation functions

The numeric algorithm mainly targets elements in containers, such as accumulate (), inner_product (), partial_sum (), adjacent_difference (), and some popular numeric algorithms. Details:

accumulate          #遍历求和,也可以用仿函数求其他数值inner_product       #内积,相应位置相乘再相加partial_sum         #部分元素之和,把结果放到后一容器中,后一容器的第n个元素师前一容器的前n个容器元素之和adjacent_difference #相邻元素之差,把结果放到后一容器中
Small Example
#include <iostream>#include <functional>#include <numeric>#include <vector>using namespace std;int main() {    int a[3] = { 2, 2, 3 };    int re = accumulate(a, a + 3, 0);    cout << re << endl;    // 7, 累加    vector<int> b;    b.push_back(2);    b.push_back(2);    b.push_back(3);    int re1 = accumulate(b.begin(), b.end(), 0, plus<int>());    cout << re1 << endl;  // 7, 累加    int re2 = accumulate(b.begin(), b.end(), 1, multiplies<int>());    cout << re2;          // 12, 累乘}

Ordered containers, heaps, and collections

binary_search    #二分法搜索,在有序容器中提高搜索速度lower_bound      #返回第一次出现该元素的位置upper_bound      #返回最后一次出现该元素的后一位置equal_range      #返回pair<lower_bound,upper_bound>inplace_merge    #将连贯有序序列合并merge            #合并两个容器includes         #判断某区间内所有的元素是否在另一区间中#堆操作push_heappop_heapsort_heapmake_heap#集合操作set_intersectionset_differenceset_symmetric_difference#最值min                       #最小max                       #最大min_element               #最小位置的迭代器max_element               #最大位置的迭代器lexicograplical_compare   #范围内的字典序比较,前后序列的比较next_permutation prev_permutation   #上一个/下一个全排列



STL note (5) algorithm Algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.