内容纲要

记录并且尝试写一些STL的内容

vector

包含了vector,algorithm,iterator三个头文件,分别代表了动态数组,copy、sort函数调用和迭代器。

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

void main() {
    vector<int> v1;
    v1.push_back(9);
    v1.push_back(8);
    v1.push_back(7);
    v1.push_back(6);
    v1.push_back(5);
    v1.push_back(4);
    v1.push_back(3);
    v1.push_back(2);
    v1.push_back(1);
    v1.push_back(0);
    vector<int>::iterator it;
    for (it = v1.begin(); it != v1.end(); it++) {
        cout << *it << endl;
    }
    for (int i = 0; i < v1.size(); i++)
    {
        cout << v1[i] << endl;
    }
        cout << "————————————————" << endl;
    v1.erase(v1.begin() + 4);
    for (int i = 0; i < v1.size(); i++)
    {
        cout << v1[i] << endl;
    }
    cout << "————————————————" << endl;
    v1[4] = 99;
    for (int i = 0; i < v1.size(); i++)
    {
        cout << v1[i] << endl;
    }
    cout << "————————————————" << endl;
    it = find(v1.begin(), v1.end(), 3);
    if (it == v1.end())
    {
        cout << "未找到" << endl;
        cout << "————————————————" << endl;
    }
    else
        cout << *it << endl;
    cout << "————————————————" << endl;
    copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, "\n"));
    cout << "————————————————" << endl;
    sort(v1.begin(), v1.end());
    copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, "\n"));

    system("pause");
}

list

除了将动态数组改为列表,和vector大同小异。

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>

using namespace std;

void main() {
    list<int> l1;
    for (int i = 0; i < 10; i++) {
        l1.push_back(rand());
    }
    copy(l1.begin(), l1.end(), ostream_iterator<int>(cout, "\n"));
    l1.sort();
    copy(l1.begin(), l1.end(), ostream_iterator<int>(cout, "\n"));

    system("pause");
}

hash_map

需要注意的是hash_map需要添加using namespace stdext,使用迭代器来防止所查找的不存在导致程序错误。

#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;

#include <hash_map>
using namespace stdext;

void main() {
    hash_map<string, string> name_phone;
    name_phone["tom"] = "123123123";
    name_phone["jarry"] = "123123111";
    name_phone["jim"] = "123123122";
    name_phone["marry"] = "123123223";
    string s;
    cin >> s;
    hash_map<string, string>::iterator it_hm = name_phone.find(s);
    if (it_hm == name_phone.end()) {
        cout << "未发现。" << endl;
    }
    else {
        cout << it_hm->first << ends << it_hm->second << endl;
    }

    system("pause");
}

1 对 “stl”的想法;

发表评论