STL--常用算法(7)

1.简介

算法部分主要由头文件<algorithm>,<numeric>和<functional>组成。

  • <algorithm>是所有STL头文件中最大的一个,其中常用到的功能范围涉及到比较、交换、查找、遍历操作、复制、修改、反转、排序、合并等等。
  • <numeric>体积很小,只包括几个在序列上面进行简单数学运算的模板函数,包括加法和乘法在序列上的一些操作。
  • <functional>中则定义了一些模板类,用以声明函数对象。

STL提供了大量实现算法的模版函数,只要我们熟悉了STL之后,许多代码可以被大大的化简,只需要通过调用一两个算法模板,就可以完成所需要的功能,从而大大地提升效率。

使用前准备:

#include <algorithm>
#include <numeric>
#include <functional>

using namespace std;
常用的查找算法:

adjacent_find()( adjacent 是邻近的意思),binary_search(),count(),

count_if(),equal_range(),find(),find_if()。

常用的排序算法:

merge(),sort(),random_shuffle()(shuffle是洗牌的意思) ,reverse()。

常用的拷贝和替换算法:

copy(), replace(),

replace_if(),swap()

常用的算术和生成算法:

accumulate()( accumulate 是求和的意思),fill(),。

常用的集合算法:

set_union(),set_intersection(),

set_difference()。

常用的遍历算法:

for_each(), transform()( transform 是变换的意思)

 

 2 例子

 

// STL算法.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <algorithm> 
//#include <numeric>
//#include <functional>
#include <iostream> 
/*#include <iterator>*/ 
#include <vector> 
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    vector<string> vecPlate;
    vecPlate.push_back("浙A5464");
    vecPlate.push_back("豫A5464");
    vecPlate.push_back("皖A5464");
    vecPlate.push_back("湘A5464");
    vecPlate.push_back("浙B5464");
    vecPlate.push_back("浙C5464");
    vecPlate.push_back("浙D5464");

    sort(vecPlate.begin(), vecPlate.end());
    std::copy(vecPlate.begin(), vecPlate.end(), std::ostream_iterator<std::string>(std::cout,"\n"));

    bool b = binary_search(vecPlate.begin(), vecPlate.end(), "浙D5464");

    return 0;
}

 

 

 

 

 

 

posted on 2013-08-08 21:22  奎哥  阅读(341)  评论(0编辑  收藏  举报