C++STL应用
- 容器与迭代器的结合
- 学生信息操作(set)
- 字符串运用(map)
容器与迭代器的结合
迭代器是一种可以遍历容器元素的数据类型。迭代器是一个变量,相当于容器和操纵容器的算法之间的中介,C++梗趋向于用迭代器而不是数组下标操作,因为标准库为每一种标准容器定义了一种迭代器类型,而只有少数容器支持数组下标操作访问容器元素。可以通过迭代器指向你想访问容器的元素地址。
vector,是数组实现,也就是说,只要知道了数组的首地址,就能访问到后面的元素。
我们可以通过将数组的下标传入函数来实现取值或是对数组元素的操作。也可以通过vector迭代器来实现。例如,在transInvT中,我们通过将传入的参数添加输出容器和函数(或对象)来实现容器与迭代器的结合。
cstl.h
#ifndef CSTL_H
#define CSTL_H
#include
void Test();
#endif // CSTL_H
cstlcpp
#include "cstl.h"
#include
#include
学生信息操作(set)
添加:push_back()方法或者insert()方法都可以实现。
删除:erase()方法实现。
查找:find()方法实现,在查找的时候,单纯用find()并不会显示是否查找成功了,所以我们可以采用iterator一个iter来接受find()返回的下标,判断下标是否越界来输出查找的结果。
修改:set是由const修饰的,不可修改,但可以先删除后增加来达到修改效果。
cstl.h
#ifndef CSTL_H
#define CSTL_H
#include
void TestSet();
#endif // CSTL_H
cstl.cpp
class studentInfo {
public:
studentInfo(string strNo, string strName) {
_strNo = strNo;
_strName = strName;
}
string _strNo;
string _strName;
friend ostream& operator<<(ostream& os, const studentInfo& info)
{
os << info._strNo << " " << info._strName;
return os;
}
friend bool operator<(const studentInfo& info1, const studentInfo& info2) {
return info1._strNo < info2._strNo;
}
};
void TestSet()
{
vector students;
students.push_back(studentInfo("10021", "Zhang san")); // 在vector最后添加一个元素
students.push_back(studentInfo("10002", "Li si"));
students.push_back(studentInfo("10003", "Wang wu"));
students.push_back(studentInfo("10011", "Wang Liu"));
students.push_back(studentInfo("10010", "Wu Liu"));
set studentSet(students.begin(), students.end()); // 定义studentSet为students的头部到尾部
outputCont("student set", cout, studentSet.begin(), studentSet.end());
studentSet.insert(studentInfo("10000","qkl")); //增加元素
outputCont("增加后student set", cout, studentSet.begin(), studentSet.end());
set::iterator iter; // 定义迭代下标来判别是否查找成功
iter=studentSet.find(studentInfo("10011","Li si")); // 查找
if(iter!=studentSet.end())
{
cout<<*iter<
字符串运用(map)
增加:数组式地添加方法,key+value。
删除:通过iterator一个iter和++的特性来遍历容器中的key,当然也可以遍历value,找到后删除,未找到继续找,知道end()。
查找:iter遍历key或value来查找。
修改:通过key修改value最直接。
输入字符串并计算其出现次数:map一个容器,从begin到end,如果没有该字符,则创建并赋值为1;如果有且为到达字符结尾,则+1。最后再map一个迭代下标来挨个输出。
cstl.h
#ifndef CSTL_H
#define CSTL_H
#include
void TestMap();
#endif // CSTL_H
cstl.cpp
#include "cstl.h"
#include
#include