zoukankan      html  css  js  c++  java
  • STL 学习

    STL概述

    STL的一个重要特点是数据结构和算法的分离。尽管这是个简单的概念,但这种分离确实使得STL变得非常通用。例如,由于STL的sort()函数是完全通用的,你可以用它来操作几乎任何数据集合,包括链表,容器和数组。

    要点

    STL算法作为模板函数提供。为了和其他组件相区别,在本书中STL算法以后接一对圆括弧的方式表示,例如sort()。

    STL另一个重要特性是它不是面向对象的。为了具有足够通用性,STL主要依赖于模板而不是封装,继承和虚函数(多态性)——OOP的三个要素。你在STL中找不到任何明显的类继承关系。这好像是一种倒退,但这正好是使得STL的组件具有广泛通用性的底层特征。另外,由于STL是基于模板,内联函数的使用使得生成的代码短小高效。

    提示

    确保在编译使用了STL的程序中至少要使用-O优化来保证内联扩展。STL提供了大量的模板类和函数,可以在OOP和常规编程中使用。所有的STL的大约50个算法都是完全通用的,而且不依赖于任何特定的数据类型。下面的小节说明了三个基本的STL组件:

    1)           迭代器提供了访问容器中对象的方法。例如,可以使用一对迭代器指定list或vector中的一定范围的对象。迭代器就如同一个指针。事实上,C++的指针也是一种迭代器。但是,迭代器也可以是那些定义了operator*()以及其他类似于指针的操作符地方法的类对象。

    2)           容器是一种数据结构,如list,vector,和deques ,以模板类的方法提供。为了访问容器中的数据,可以使用由容器类输出的迭代器。

    3)           算法是用来操作容器中的数据的模板函数。例如,STL用sort()来对一个vector中的数据进行排序,用find()来搜索一个list中的对象。函数本身与他们操作的数据的结构和类型无关,因此他们可以在从简单数组到高度复杂容器的任何数据结构上使用。

    头文件

    为了避免和其他头文件冲突, STL的头文件不再使用常规的.h扩展。为了包含标准的string类,迭代器和算法,用下面的指示符:

    #include <string>

    #include <iterator>

    #include <algorithm>

    如果你查看STL的头文件,你可以看到象iterator.h和stl_iterator.h这样的头文件。由于这些名字在各种STL实现之间都可能不同,你应该避免使用这些名字来引用这些头文件。为了确保可移植性,使用相应的没有.h后缀的文件名。表1列出了最常使用的各种容器类的头文件。该表并不完整,对于其他头文件,我将在本章和后面的两章中介绍。

    表 1. STL头文件和容器类

    #include

    Container Class

    <deque>

    deque

    <list>

    list

    <map>

    map, multimap

    <queue>

    queue, priority_queue

    <set>

    set, multiset

    <stack>

    stack

    <vector>

    vector, vector<bool>

    名字空间

    你的编译器可能不能识别名字空间。名字空间就好像一个信封,将标志符封装在另一个名字中。标志符只在名字空间中存在,因而避免了和其他标志符冲突。例如,可能有其他库和程序模块定义了sort()函数,为了避免和STL地sort()算法冲突,STL的sort()以及其他标志符都封装在名字空间std中。STL的sort()算法编译为std::sort(),从而避免了名字冲突。

    尽管你的编译器可能没有实现名字空间,你仍然可以使用他们。为了使用STL,可以将下面的指示符插入到你的源代码文件中,典型地是在所有的#include指示符的后面:

    using namespace std;

    迭代器

    迭代器提供对一个容器中的对象的访问方法,并且定义了容器中对象的范围。迭代器就如同一个指针。事实上,C++的指针也是一种迭代器。但是,迭代器不仅仅是指针,因此你不能认为他们一定具有地址值。例如,一个数组索引,也可以认为是一种迭代器。

    迭代器有各种不同的创建方法。程序可能把迭代器作为一个变量创建。一个STL容器类可能为了使用一个特定类型的数据而创建一个迭代器。作为指针,必须能够使用*操作符类获取数据。你还可以使用其他数学操作符如++。典型的,++操作符用来递增迭代器,以访问容器中的下一个对象。如果迭代器到达了容器中的最后一个元素的后面,则迭代器变成past-the-end值。使用一个past-the-end值得指针来访问对象是非法的,就好像使用NULL或为初始化的指针一样。

    提示

    STL不保证可以从另一个迭代器来抵达一个迭代器。例如,当对一个集合中的对象排序时,如果你在不同的结构中指定了两个迭代器,第二个迭代器无法从第一个迭代器抵达,此时程序注定要失败。这是STL灵活性的一个代价。STL不保证检测毫无道理的错误。

    迭代器的类型

    对于STL数据结构和算法,你可以使用五种迭代器。下面简要说明了这五种类型:

    ·        Input iterators 提供对数据的只读访问。

    ·        Output iterators 提供对数据的只写访问

    ·        Forward iterators 提供读写操作,并能向前推进迭代器。

    ·        Bidirectional iterators提供读写操作,并能向前和向后操作。

    ·        Random access iterators提供读写操作,并能在数据中随机移动。

    尽管各种不同的STL实现细节方面有所不同,还是可以将上面的迭代器想象为一种类继承关系。从这个意义上说,下面的迭代器继承自上面的迭代器。由于这种继承关系,你可以将一个Forward迭代器作为一个output或input迭代器使用。同样,如果一个算法要求是一个bidirectional 迭代器,那么只能使用该种类型和随机访问迭代器。


    转载学习 一下 各个函数怎么用的~_~

    //STL_study.cpp
    #include "stdafx.h"
     #include <iostream.h>
     #include <algorithm>
     #include <vector>
     
     using namespace std;

    指针迭代器

     #define SIZE 100
     int iarray[SIZE];
      
     int main()
     {
       iarray[20] = 50;
       int* ip = find(iarray, iarray + SIZE, 50);
       if (ip == iarray + SIZE)
     	  cout << "50 not found in array" << endl;
       else
     	  cout << *ip << " found in array" << endl;
       return 0;
     }

    容器迭代器

    vector<int> intVector(100);
     
     int main()
     {
     	intVector[20] = 50;
     	vector<int>::iterator intIter = find(intVector.begin(), intVector.end(),50);
     	if (intIter != intVector.end())
     	{
     		cout<<"Vector contains value"<<*intIter <<endl;
     	}
     	else
     		cout<<"Vector does not contain 50";
     	return 0;
     }

    常量迭代器

     vector<int> intVector(100);
     vector<int>::iterator first = intVector.begin();
     
     int main()
     {
     	*first = 50;
     	first = find(intVector.begin(), intVector.end(),50);
     	if (first != intVector.end())
     	{
     		cout<<"Vector contains value"<<*first <<endl;
     	}
     	else
     		cout<<"Vector does not contain 50";
     	return 0;
     }

    输入迭代器

     template <class InputIterator, class T>
     InputIterator find(find模板定义
     				   InputIterator first, InputIterator last, const T& value) {
         while (first != last && *first != value) ++first;
         return first;
       }

    输出迭代器

     double darray[10] =  {1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9};
     vector<double> vdouble(10);
     
     int main()
     {
     	vector<double>::iterator outputIterator = vdouble.begin();
     	copy(darray,darray+10,outputIterator);
     	while(outputIterator != vdouble.end())
     	{
     		cout<<*outputIterator<<endl;
     		outputIterator++;
     	}
     	return 0;
     }

    前推迭代器

     template <class ForwardIterator, class T>
     void replace (ForwardIterator first,
                   ForwardIterator last,
                   const T& old_value,
                   const T& new_value);
     使用replace()将[first,last]范围内的所有值为old_value的对象替换为new_value。:
    双向迭代器
     template <class BidirectionalIterator>
     void reverse (BidirectionalIterator first,
                   BidirectionalIterator last);
     使用reverse()函数来对容器进行逆向排序:
    reverse(vdouble.begin(), vdouble.end());
    随机访问迭代器
     random_shuffle() 函数随机打乱原先的顺序。申明为:
     
     template <class RandomAccessIterator>
     void random_shuffle (RandomAccessIterator first,
                          RandomAccessIterator last);
     使用方法:
     random_shuffle(vdouble.begin(), vdouble.end());

    流和迭代器

    #include <iostream>
     #include <stdlib.h>     Need random(), srandom()
     #include <time.h>       Need time()
     #include <algorithm>    Need sort(), copy()
     #include <vector>       Need vector
     
     using namespace std;
     
     void Display(vector<int>& v, const char* s);
     bool UDgreater ( int elem1, int elem2 )
     {
     	return elem1 > elem2;
     }
     
     int main()
     {
     	 Seed the random number generator
     	srand( time(NULL) );
     	
     	 Construct vector and fill with random integer values
     	vector<int> collection(10);
     	for (int i = 0; i < 10; i++)
     		collection[i] = rand() % 10000;;
     	
     	 Display, sort, and redisplay
     	Display(collection, "Before sorting");
     	sort(collection.begin(), collection.end(),UDgreater);
     	Display(collection, "After sorting");
     	return 0;
     }
     
      Display label s and contents of integer vector v
     void Display(vector<int>& v, const char* s)
     {
     	cout << endl << s << endl;
     	copy(v.begin(), v.end(),
     		ostream_iterator<int>(cout, "	"));The delimiter that is inserted into the output stream between values.
     	cout << endl;
     }

    插入迭代器

     三种插入迭代器如下:
     
     ·        普通插入器 将对象插入到容器任何对象的前面。
     象插入到数据集的前面——例
     ·        Front inserters 将对如,链表表头。
     
     ·        Back inserters 将对象插入到集合的尾部——例如,矢量的尾部,导致矢量容器扩展。

     
    #include <iostream>
     #include <algorithm>
     #include <list>
     
     using namespace std;
     
     int iArray[5] = {1,2,3,4,5};
     
     void Display(list<int>& v, const char* s);
     int main()
     {
     	list<int> iList,iList2;
     	 Copy iArray backwards into iList
     	copy(iArray, iArray + 5, front_inserter(iList));
     	Display(iList, "1 Before find and copy");
     
     	copy(iArray, iArray + 5, back_inserter(iList2));
     	Display(iList2, "2 Before find and copy");
     `
     	 Locate value 3 in iList
     	list<int>::iterator p = find(iList.begin(), iList.end(), 3);
     	 Copy first two iArray values to iList ahead of p
     	copy(iArray, iArray + 2, inserter(iList, p));
     	Display(iList, "After find and copy");
     	return 0;
     }
     
     void Display(list<int>& a, const char* s)
     {
     	cout << s << endl;
     	copy( a.begin(), a.end(),ostream_iterator<int>(cout, " ") );
     	cout << endl;
     }

    混合迭代器函数

     advance() 按指定的数目增减迭代器。
     distance() 返回到达一个迭代器所需(递增)操作的数目。

    #include <iterator>
     #include <list>
     #include <iostream>
     
     int main( )
     {
        using namespace std;
        int i;
     
        list<int> L;
        for ( i = -1 ; i < 9 ; ++i ) 
        {
           L.push_back ( 2 * i );
        }
        list <int>::iterator L_Iter, LPOS = L.begin ( );
     
        cout << "The list L is: ( ";
        for ( L_Iter = L.begin( ) ; L_Iter != L.end( ); L_Iter++ )
           cout << *L_Iter << " ";
        cout << ")." << endl;
        
        cout << "The iterator LPOS initially points to the first element: "
     	   << *LPOS << "." << endl;
        
        advance ( LPOS , 7 );寻找距离参数2的值
        cout << "LPOS is advanced 7 steps forward to point "
     	   << " to the eighth element: "
     	   << *LPOS << "." << endl;
        
        list<int>::difference_type Ldiff ;
        Ldiff = distance ( L.begin ( ) , LPOS );距离
        cout << "The distance from L.begin( ) to LPOS is: "
     	   << Ldiff << "." << endl;
     }
     The list L is: ( -2 0 2 4 6 8 10 12 14 16 ).
     The iterator LPOS initially points to the first element: -2.
     LPOS is advanced 7 steps forward to point  to the eighth element: 12.
     The distance from L.begin( ) to LPOS is: 7.

    函数和函数对象 24个数 计算有多少负数

    #include <iostream>
     #include <stdlib.h>      Need random(), srandom()
     #include <time.h>        Need time()
     #include <vector>        Need vector
     #include <algorithm>     Need for_each()
     
     using namespace std;
     #define VSIZE 24         Size of vector
     vector<long> v(VSIZE);   Vector object
     
      Set ri to a signed integer value
     void initialize(long &ri)
     {
     	ri = ( rand() - (RAND_MAX / 2) );
     	  ri = random();
     }
      Display value of ri
     void show(const long &ri)
     {
     	cout << ri << "  ";
     	printf("0x%x ",ri);
     }
      Returns true if ri is less than 0
     bool isMinus(const long &ri)
     {
     	return (ri < 0);
     }
     
     int main()
     {
     	srand( time(NULL) );   Seed random generator
     	for_each(v.begin(), v.end(), initialize);调用普通函数
     	cout << "Vector of signed long integers" << endl;
     	for_each(v.begin(), v.end(), show);
     	cout << endl;
     	
     	 Use predicate function to count negative values
     	
     	int count = 0;
     	vector<long>::iterator p;
     	p = find_if(v.begin(), v.end(), isMinus);调用断言函数
     	while (p != v.end()) {
     		count++;
     		p = find_if(p + 1, v.end(), isMinus);
     	}
     	cout << "Number of values: " << VSIZE << endl;
     	cout << "Negative values : " << count << endl;
     	
     	return 0;
     }

    函数对象 10个数相加 相乘

    #include <iostream>
     #include <numeric>       Need accumulate()
     #include <vector>        Need vector
     #include <functional>    Need multiplies() (or times())
     #include <algorithm>
     
     using namespace std;
     #define MAX 10
     vector<long> v(MAX);     Vector object
     
     void show(const long &ri)
     {
     	printf("%d ",ri);
     }
     int main()
     {
     	 Fill vector using conventional loop
     	
     	for (int i = 0; i < MAX; i++)
     		v[i] = i + 1;
     	for_each(v.begin(),v.end(),show);
     	 Accumulate the sum of contained values
     	long sum = accumulate(v.begin(), v.end(), 0);该函数计算容器中所有值的总和
     	cout << "
    Sum of values == " << sum << endl;55
     	
     	 Accumulate the product of contained values
     	long product = accumulate(v.begin(), v.end(), 1, multiplies<long>());注意这行 multiplies(1,v)计算乘积
     	cout << "Product of values == " << product << endl;3628800
     	
     	return 0;
     }
     1 2 3 4 5 6 7 8 9 10
     Sum of values == 55
     Product of values == 3628800

    发生器函数对象 随机输出10个数

    #include <iostream>
     #include <stdlib.h>     Need random(), srandom()
     #include <time.h>       Need time()
     #include <algorithm>    Need random_shuffle()
     #include <vector>       Need vector
     #include <functional>   Need ptr_fun()
      
     using namespace std;
       
      Data to randomize
     int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
     vector<int> v(iarray, iarray + 10);
       
      Display contents of vector vr
     void Display(vector<int>& vr, const char *s)
     {
     	cout << endl << s << endl;
     	copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " "));
     	cout << endl;
     }
      Return next random value in sequence modulo n
     unsigned int RandInt(unsigned int n)
     {
     	return rand() % n;
     	return n;
     }
     int main()
     {
       srand( time(NULL) );   Seed random generator
       Display(v, "Before shuffle:");
       
       pointer_to_unary_function<unsigned int, unsigned int> ptr_RandInt = ptr_fun(RandInt);   Pointer to RandInt() 注意这行
       random_shuffle(v.begin(), v.end(), ptr_RandInt);
     
       Display(v, "After shuffle:");
       return 0;
     }

    发生器函数类对象 随机输出10个数

     #include <iostream>
     #include <algorithm>    Need random_shuffle()
     #include <vector>       Need vector
     #include <functional>   Need unary_function
     
     using namespace std;
     
      Data to randomize
     int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
     vector<int> v(iarray, iarray + 10);
     
      Display contents of vector vr
     void Display(vector<int>& vr, const char *s)
     {
     	cout << endl << s << endl;
     	copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " "));
     	cout << endl;
     }
      The FiboRand template function-object class
     template <class Arg>
     class FiboRand : public unary_function<Arg, Arg> {
     	int i, j;
     	Arg sequence[18];
     public:
     	FiboRand();
     	Arg operator()(const Arg& arg);
     };
     
      FiboRand class constructor
     template<class Arg>
     FiboRand<Arg>::FiboRand()
     {
     	sequence[17] = 1;
     	sequence[16] = 2;
     	for (int n = 15; n > 0; n--)
     		sequence[n] = sequence[n + 1] + sequence[n + 2];
     	i = 17;
     	j = 5;
     }
     
      FiboRand class function operator
     template<class Arg>
     Arg FiboRand<Arg>::operator()(const Arg& arg)
     {
     	Arg k = sequence[i] + sequence[j];
     	sequence[i] = k;
     	i--;
     	j--;
     	if (i == 0) 
     		i = 17;
     	if (j == 0) 
     		j = 17;
     	return k % arg;
     }
     void main()
     {
     	FiboRand<int> fibogen;   Construct generator object
     	cout << "Fibonacci random number generator" << endl;
     	cout << "using random_shuffle and a function object" << endl;
     	Display(v, "Before shuffle:");
     	random_shuffle(v.begin(), v.end(), fibogen);
     	Display(v, "After shuffle:");
     }






  • 相关阅读:
    tf导出pb文件,以及如何使用pb文件
    word2vec入门理解的博客整理
    简单的RNN和BP多层网络之间的区别
    图像中用到的信息论中的一些概念公式
    raw文件转mha文件
    mha格式的CT体数据转为jpg切片
    在MySQL的表中增加一列
    ES7学习笔记(二)ES的集群原理
    MySQL中的幻读,你真的理解吗?
    ES7学习笔记(一)Elasticsearch的安装与启动
  • 原文地址:https://www.cnblogs.com/zcc1414/p/3982329.html
Copyright © 2011-2022 走看看