美文网首页
第16章:string类和标准模板库

第16章:string类和标准模板库

作者: YBHello | 来源:发表于2018-01-29 22:24 被阅读0次

/* 使用结构来记录知识 - 知识体系 */
本章节复习了 string 类,但其重点为标准模板库的介绍。这里将采用:3+2+1 的方式来记录本章节知识点(为什么使用数字:1. 使用数字的方式更直观 2. 重新整理顺序、便于逻辑记忆):

1. 三个简单知识点

  • a. string 类:初始化,用于输入、输出,其他一些方法(.size、.find等)
  • b. 智能指针:unique_ptr、shared_ptr、auto_ptr(弃用)
  • c. 函数对象:重载了 () 符号的对象,可被直接调用;bind1st、bind2nd;+ -> plus、* -> multiplies 等运算符到函数符的转换。

2. 两个标准模板库知识

  • a. 容器、迭代器、算法原理:
  1. 容器:实现了对应结构体描述的方法的模板类。
  2. 迭代器:实现了 ++、*(解引用)、.begin、.end 等方法的模板类。
  3. 算法:实现了数学算法描述的功能的模板。
  • b. 容器、迭代器、算法范例:verctor、deque、list、stack;xx.begin、xx.end;copy、transform 等

3. 一个其他

  • a. valarray、array、initializer_list

简单使用范例代码:

/**
 * 16. string 和 标准模板库
 *      1. string
 *      2. 容器 set 的使用
 *      3. 算法 set_union
 *      4. 迭代器 基本循环和 insert_iterator
 */
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <iterator>

using namespace std;



int main()
{
    cout << "Hello world!" << endl;

    int i = 0;
    string input;

    set<string> mat_friends;
    set<string> pat_friends;
    set<string> all_friends;

    set<string>::iterator p;

    do {
        cout << "input mat's friends name:(# to quit.) : ";
        cin >> input;
        if (input == "#")
        {
            break;
        }
        mat_friends.insert(input);

    } while (1);


    for (p = mat_friends.begin(), i = 0; p != mat_friends.end(); p++, i++)
    {
        cout << i << " : " << *p << endl;
    }

    do {
        cout << "input pat's friend name:(# to quit.) : ";
        cin >> input;
        if (input == "#")
        {
            break;
        }
        pat_friends.insert(input);
    } while (1);


    for (p = pat_friends.begin(), i++; p != pat_friends.end(); p++, i++)
    {
        cout << i << " : " << *p << endl;
    }

    cout << endl << "All friend:" << endl;

    set_union(mat_friends.begin(), mat_friends.end(),
                   pat_friends.begin(), pat_friends.end(),
                   insert_iterator<set<string> >(all_friends, all_friends.begin()));   // 这里是 >(space)>


    for (p = all_friends.begin(), i = 0; p != all_friends.end(); p++, i++)
    {
        cout << i << " : " << *p << endl;
    }

    cout << endl << "Another way to print: " << endl;

    ostream_iterator<string, char> out(cout , "\n");

    set_union(mat_friends.begin(), mat_friends.end(),
              pat_friends.begin(), pat_friends.end(),
              out);


    return 0;
}

我是伍栎,一个用文字记录成长的程序猿。:)

相关文章

网友评论

      本文标题:第16章:string类和标准模板库

      本文链接:https://www.haomeiwen.com/subject/xnwfzxtx.html