C++知识点分享008 stl使用:string、iostream、vector、list、map

微信公众号: 星点课堂

新浪微博:女儿叫老白

网易云课堂:女儿叫老白

-------------------------------------------------------------------------------

如果进行服务端编程,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;      // 这样写是防止使用 using namespace导致命名空间污染,

using std::endl;   // 用到啥就写啥。

using std::cin;

 

// 下面语句将内容输出到流(除非做过重定向,一般是输出到终端)

cout <<”我想说的是:” << str << endl;

 

// 下面的语句从输入输出流获取一个键盘输入字符。

char ch = ‘\0’;

cin >> ch;

 

---------------------------------

// 数组 vector

vector 是模板类

vector<int> v1;         // 声明一个数组,它的成员是int类型。

vector<double> v2;     // 声明一个数组,它的成员是double类型。

 

v1.push_back(2);          // 向v1中压入一个数值,push_back()表示压到数组的最后一个

                                   // v1变成: 2

v1.push_back(5);          // 向v1中压入一个数值,push_back()表示压到数组的最后一个

                                   // v1变成: 2, 5

 

v1.push_front(3);          // 向v1中压入一个数值,push_back()表示压到数组的最前一个

                                   // v1变成: 3,  2,  5

 

有两种方式对vector进行遍历,

// 方法1:用下标

for (int i=0; i<v1.size(); i++) {

    cout << v[i] << endl;

}

 

// 方法2:使用迭代器

vector<int>::iterator ite = 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>::iterator iteLst = lst.begin();

iteLst = lst.find(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 whose id = 201” << endl;

}

猜你喜欢

转载自blog.csdn.net/baizy77/article/details/82320826