STL——算法

以下内容大多摘自《C++标准程序库》

STL提供了一些标准算法,包括搜寻、排序、拷贝、重新排序、修改、数值运算等。算法并不是容器类别的成员函数,而是一种搭配迭代器使用的全局函数。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> coll;
    vector<int>::iterator pos;
    //coll.push_back(2);
    coll.push_back(5);
    coll.push_back(4);
    coll.push_back(1);
    coll.push_back(6);
    coll.push_back(3);

    pos = min_element(coll.begin(),coll.end());    //寻找最小值
    cout << "min:" << *pos << endl;
    pos = max_element(coll.begin(), coll.end());//寻找最大值
    cout << "max:" << *pos << endl;

    sort(coll.begin(),coll.end());  //排序
    cout << "sort:";
    for (pos = coll.begin(); pos != coll.end(); ++pos) {
        cout << *pos << ' ' ;
    }
    cout << endl;       //这里输出的是  1 2 3 4 5 6
    pos = find(coll.begin(),coll.end(), 3);   //找到值为3的第一个元素
    cout << "find:";
    cout << *pos << endl;   

    reverse(pos,coll.end());  //反转pos及以后的所有元素,因为前面把pos知道了3的位置,所以这样操作就是反转3到以后的元素,前面的find()就是用来打辅助的
    
    for (pos = coll.begin(); pos != coll.end(); ++pos) {
        cout << *pos << ' ';
    }
    cout << endl;
    system("pause");
}

最后输出:

min:1
max:6
sort:1 3 4 5 6
find:3
1 6 5 4 3

来源:张家港网站优化

猜你喜欢

转载自www.cnblogs.com/1994july/p/12152740.html