STL algorithm

作者:jicanmeng

时间:2017年06月21日


To use any of the STL algorithms, simply include the algorithm header file. 算法当然有很多,STL中提供了很多算法。例如:

寻找最大值和寻找最小值:

#include <iostream>
#include <list>
#include <algorithm>

int main()
{
    using namespace std;

    list<int> li;
    for (int nCount = 0; nCount < 6; nCount++)
        li.push_back(nCount);

    list<int>::const_iterator it; // declare an iterator
    it = min_element(li.begin(), li.end());
    cout << *it << " ";
    it = max_element(li.begin(), li.end());
    cout << *it << " ";

    cout << endl;
}

运行结果如下:

[jicanmeng@andy tmp]$ ./a.out
                0 5
			[jicanmeng@andy tmp]$

找到对应的元素并插入一个新元素:

#include <iostream>
#include <iostream>
#include <list>
#include <algorithm>

int main()
{
    using namespace std;

    list<int> li;
    for (int nCount = 0; nCount < 6; nCount++)
        li.push_back(nCount);

    list<int>::iterator it; // declare an iterator
    it = find(li.begin(), li.end(), 3); // find the value 3 in the list
    li.insert(it, 8); // use list::insert to insert the value 8 before it

    for (it = li.begin(); it != li.end(); it++) // for loop with iterators
        cout << *it << " ";

    cout << endl;
}

以下是运行结果:

[jicanmeng@andy tmp]$ ./a.out
                0 1 2 8 3 4 5
			[jicanmeng@andy tmp]$

参考资料

  1. <<C++实用教程>> 电子工业出版社 郑阿奇 主编 丁有和 编著 P280
  2. The C++ Tutorial:
    http://www.learncpp.com/cpp-tutorial/16-1-the-standard-template-library-stl/
  3. misc:
    http://www.cnblogs.com/shiyangxt/archive/2008/09/11/1289493.html 简单的程序诠释C++ STL算法系列之二:find