C++之list-map的简单使用

list 链表

链表是由节点之间通过指针连接而成的链式结构存储结构体,对于链表,C++标准库中已经提供了封装好的链表了。

 #include<list>  //包含头文件

using namespace std;  //打开标准命名空间

定义链表,并在首尾添加和删除元素:

	list<int>lst;//定义链表对象,list后<>中指定链表类型
	lst.push_front(0);//链表头添加
	lst.push_back(1);//链表尾添加
	lst.pop_front();//删除头结点
	lst.pop_back();//删除尾结点

迭代器遍历链表:

	//迭代器遍历链表
	list<int>::iterator ite = lst.begin();//定义迭代器指向头结点
	while (ite != lst.end()) {
		cout << *ite << "  ";
		ite++;
	}

使用增强范围的for循环遍历链表:

	//使用增强范围的for循环遍历链表
	for (int v : lst) {
		cout << v << "  ";
	}

加引用可以修改节点里的值:

	//加引用可以修改节点里面的值
	for (int& v : lst) {
		v = value;
	}

 其他常见函数:

lst.empty();  //判断当前链表是否为空(bool类型),空返回true,非空返回false
lst.size();   //获取链表的长度
lst.clear();  //清空链表,empty 为 ture,size 为 0

对链表进行排序 

#include<list>
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
	list<int>lst{ 0,2,1,3,5,4 };
	//降序排序 也可直接写成lst.sort()
	lst.sort(less<int>());
	//升序排序
	//lst.sort(greater<int>());
	list<int>::iterator ite= lst.begin(); 
	while (ite != lst.end()) {
		cout << *ite << " ";
		ite++;
	}
	cout << endl;
}

 

 map 映射表

map 为映射表,每一个元素称之为键值对 (pair) ,有键值 (key) 和 实值(value)两部分,键值不能重复,所有元素都会根据元素的键值自动被排序

#include<map> 包含头文件

using namespace std; 打开标准命名空间

定义map  格式: map<key,value> mm;

    map<char, int> mm;

添加元素   格式: mm[key] = value;

    mm['b'] = 1; 
    mm['d'] = 2;
    mm['a'] = 3;  
    mm['c'] = 4;

使用函数插入元素

mm.insert(pair<char, int>('e', 5));

迭代器遍历map

    map<char, int>::iterator ite = mm.begin();
    while (ite != mm.end()) {
        //first : 键值,后面不要加(),second : 实值
        cout << ite->first << "-" << ite->second << "   ";
            ite++;
    }
    cout << endl;

 修改  当键值已经存在时,会直接修改实值

mm['c']=40;

删除  参数迭代器默认会失效,所以一般情况下会接一下返回值,返回的是删除的下一个元素

    ite = ++mm.begin();
    ite = mm.erase(ite); 

for循环遍历 

    for (pair<char,int> pr : mm) {
        cout << pr.first << "-" << pr.second << "  ";
    }
    cout << endl;
 

 使用引用,可以修改实值 

    for (pair<const char,int>& pr : mm) {//注意: 因键值不能修改,故const不能省略否则报错
        ...
        if (pr.first == key) {
            pr.second = value;
        }
        ...
    }

count  按照键值统计,可用于判断键值是否存在

    int count = mm.count('B');  
    cout << count << endl;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值