Linux C++ STL用法介紹(1)


 

STL = Standard Template Library,標准模板庫,惠普實驗室開發的一系列軟件的統稱。它是由Alexander Stepanov、Meng Lee和David R Musser在惠普實驗室工作時所開發出來的。這可能是一個歷史上最令人興奮的工具的最無聊的術語。從根本上說,STL是一些“容器”的集合,這些“容器”有list,vector,set,map等,STL也是算法和其他一些組件的集合。這里的“容器”和算法的集合指的是世界上很多聰明人很多年的傑作。STL的目的是標准化組件,這樣就不用重新開發,可以使用現成的組件。STL現在是C++的一部分,因此不用額外安裝什么。在C++標准中,STL被組織為下面的13個頭文件:<algorithm>、<deque>、<functional>、<iterator>、<vector>、<list>、<map>、<memory>、<numeric>、<queue>、<set>、<stack>和<utility>。

1) STL 基礎

stl 算法知識

Using the STL generic reverse algorithm with an array

Use random_shuffle algorithms with array

#include <iostream>
#include <string>
#include <cassert>
#include <algorithm> // For reverse algorithm
using namespace std;

int main()
{

char array1[] = "abc";
int N1 = strlen(array1);
int a[100], b[100];
int i;

reverse(&array1[0], &array1[N1]);
for (i = 0; i < N1; i++)
cout << "array1[" << i << "] = " << array1[i] << endl;
for (i = 0; i < 100; ++i)
a[i] = i;
reverse_copy(&a[0], &a[100], &b[0]);
for (i = 0; i < 100; i++)
cout << "a: " << a[i] << " -- b: " << b[i] << endl;

random_shuffle(&a[0], &a[100]);

for (i = 0; i < 100; i++)
    cout << " " << a[i] << " ";
return 0;
}

1.2 巧用 C++ 函數模板

Using function templates to get the max and min value in an array

#include <iostream>
using std::cout;
using std::endl;


template<class T> T max(const T* data, int size) {
    T result = data[0];
    for(int i = 1 ; i < size ; i++)
      if(result < data[i])
        result = data[i];
    return result;
  }

template<class T> T min(const T* data, int size) {
    T result = data[0];
    for(int i = 1 ; i < size ; i++)
      if(result > data[i])
        result = data[i];
    return result;
  }

 

int main() {
  double data[] = {1.5, 4.6, 3.1, 1.1, 3.8, 2.1};
  int numbers[] = {2, 22, 4, 6, 122, 12, 1, 45};

  const int dataSize = sizeof data/sizeof data[0];
  cout << "Minimum double is " << min(data, dataSize) << endl;
  cout << "Maximum double is " << max(data, dataSize) << endl;

  const int numbersSize = sizeof numbers/sizeof numbers[0];
  cout << "Minimum integer is " << min(numbers, numbersSize) << endl;
  cout << "Maximum integer is " << max(numbers, numbersSize) << endl;

  return 0;
}

/*
Minimum double is 1.1
Maximum double is 4.6
Minimum integer is 1
Maximum integer is 122

 */

 Use back_insert_iterator to insert element into a vector

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM