作者: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]$