本帖最后由 baizy77 于 2020-4-21 09:22 编辑
版权声明 --------------------------------------------------------------------------------------------------------------------- 作者: 女儿叫老白 (白振勇) 转载请注明出处! --------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------
引言 ----------------------------------------------------------------------------- 在C++软件开发过程中,我们会用到各式各样的类库,其中,经常用到的就是stl(标准模板库)。它为我们解决了很多问题,今天我们就来看一下,几个常用的模板类的用法。
正文 ----------------------------------------------------------------------------- 如果进行服务端编程,stl、poco等库都是不错的选择。我们今天分享一下stl部分类的使用。 --------------------------------- // 字符串类string. include<string>
一般用到获取字符串的连接,比如: string str1 =“abc”; string str2 =“,..def”; string str =str1+str2;
或者获取字符串内容,比如: str.c_str()
--------------------------------- // 输入输出流iostream #include<iostream> using std::cout; // 这样写是防止使用 usingnamespace导致命名空间污染, usingstd::endl; // 用到啥就写啥。 using std::cin;
// 下面语句将内容输出到流(除非做过重定向,一般是输出到终端) cout <<”我想说的是:” << str << endl;
// 下面的语句从输入输出流获取一个键盘输入字符。 char ch = ‘\0’; cin >> ch;
--------------------------------- // 数组 vector // vector 是模板类 std::vector<int>v1; // 声明一个数组,它的成员是int类型。 std::vector<double>v2; // 声明一个数组,它的成员是double类型。
v1.push_back(2); // 向v1中压入一个数值,push_back()表示压到数组的最后一个 // v1变成: 2 v1.push_back(5); // 向v1中压入一个数值,push_back()表示压到数组的最后一个 // v1变成: 2, 5
std::vector<int>::iterator iteVec = v1.begin(); v1.insert(iteVec, 3); // 向v1中压入一个数值,因为iteVec指向数组的开头,所以此处的insert()表示压到数组的最前一个 // v1变成: 3, 2, 5
有两种方式对vector进行遍历, // 方法1:用下标 for (int i=0;i<v1.size(); i++) { cout << v << endl; }
// 方法2:使用迭代器 vector<int>::iteratorite = v1.begin(); for (; ite !=v1.end(); ite++) { cout << *ite << endl; }
v1.clear(); // 清空数组v1.
// 删除值=2的成员 ite =v1.begin(); for (;ite!=v1.end();) { if ((*ite) == 2) { v1.erase(ite++); // 该语法可以删除当前成员,并且将迭代器+1 } else{ ite++; } }
--------------------------------- // 列表 list 列表在内存中一般不会连续排列 列表一般通过迭代器方式访问 list<float>lst; lst.push_back(1.f); lst.push_back(13.f);
list<float>::iteratoriteLst = lst.begin(); iteLst =find(lst.begin(), lst.end(), 13.f); if (iteLst !=lst.end()) { // 找到了 cout<< “data 13.f founded!” << endl; } else { cout << “cannot find data 13.f”<< endl; } 列表遍历,如下: iteLst =lst.begin(); for (; ite !=lst.end(); iteLst++) { cout << *iteLst << endl; }
--------------------------------- // 映射 map 一般我们用到键值对时会用到map,比如通过学号找某个学员的相关信息 class CStudent {}; 假定学号为int类型; map<int,CStudent> mapID2Student;
CStudent stud1,stud2; mapID2Student[201]= stud1; // 学号=201,对应学员stud1; mapID2Student[202]= stud2; // 学号=202,对应学员stud2;
// 搜索某个学员 map<int,CStudent>::iterator iteMap = mapID2Student.find(201);// 搜索id=201的学员 if (iteMap != mapID2Student.end()){ cout << “id=201, student founded”<< endl; } else { cout << “cannot find student whoseid = 201” << endl; } |