C Plus Plus

本文最后更新于:9 个月前

C++ 的泛型程序设计思想

  • C++ 语言的核心优势之一就是便于软件的重用
  • C++中有两个方面体现重用:

    1. 面向对象的思想:继承和多态,标准类库
    2. 泛型程序设计(generic programming) 的思想: 模板机
      制,以及标准模板库 STL

    先看一段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <list>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <deque>
using namespace std;

int main(void)
{
string string_hello = "Hello";
string_hello += string_hello;
list<int> list_hello;
list_hello.push_front(100);
list_hello.push_back(200);
list<int>::const_iterator point;
for(point = list_hello.begin(); point != list_hello.end(); point++)
cout << *point << endl;
vector<int> vec;
vec.push_back(23);
vec.push_back(89);
vec.push_back(123);
vec.push_back(333);
vector<int>::iterator p;
vec.reserve(1000);
p = find(vec.begin(), vec.end(), 333);
if (p != vec.end())
cout << vec.size() <<endl << vec.capacity() << endl;
if (!vec.empty()) {
cout << "Vector is not empty" << endl;
}
vec.resize(2000);
cout << vec.capacity() << endl;
vector<int> arrays{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ostream_iterator<int> it(cout, " ");
copy(arrays.begin(), arrays.end(), it);
deque<int> deq1{1, 2, 3};
ostream_iterator<int> its(cout, " ");
copy(deq1.begin(), deq1.end(), its);
return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!