STL小结1

本文详细解释了C++STL中的fill和memset在内存赋值上的区别,并通过map和vector、pair的混合使用示例,展示了如何根据key或value对map进行排序,以及vector中删除元素的方法和不同的遍历方式。
摘要由CSDN通过智能技术生成

fill和memset的区别

memset按字节为单位依次赋值,而fill以数据变量类型为单位赋值。

int a[10];
bool b[10];
//用1填充40个byte
memset(a, 1, sizeof(a)); //0x01010101
//用1填充10个int
fill(a, a+10, 1); //0x00000001
//用1填充10个byte
memset(b, 1, sizeof(b)); //0x01
//其他常见的给数组赋初值
memset(a, 0, sizeof(a)); //0x00000000 --清零
memset(a, -1, sizeof(a)); //0xffffffff -- 赋最小值
memset(a, 0x3f, sizeof(a)); //0x3f3f3f3f --赋最大值

map,vector和pair混合使用的例子

  1. map不能排序,因为map内部用红黑树实现 ,已具有内部排序机制。
    如果想map进行排序,可以先将map元素转换为vector里的pair元素, 然后根据map的key(pair的first)或者map的value(pair的second)排序。
  2. vector里删除元素,用erase()函数,它接受iterator类型参数。
  3. .begin(), .end()返回的都是iterator, 前闭后开。
  4. 遍历容器用的也是iterator。
#include<bits/stdc++.h>
using namespace std;
map<int, int> color;

int main(){
	color.insert(make_pair(5, 11));
	color.insert(make_pair(7, 13));
	color.insert(make_pair(6, 21));
	color.insert(make_pair(8, 13));
	color.insert(make_pair(0, 12));
	color.insert(make_pair(12, 0));
	
	vector<pair<int, int>> ncolor(color.begin(), color.end());
	//按pair.first(即map.key)排序
	sort(ncolor.begin(), ncolor.end());
	cout<<"按key排序:"<<endl;
	for(auto &p:ncolor) {
		cout<<p.first<<" "<<p.second<<endl;
	}
	//按pair.second(即map.value)排序
	sort(ncolor.begin(), ncolor.end(), 
		[](const pair<int, int>& a, const pair<int, int>& b) {
            return a.second < b.second;
		});
	cout<<"按value排序:"<<endl;
	for(auto &p:ncolor) {
		cout<<p.first<<" "<<p.second<<endl;
	} 
	//删除vector里的元素,删除后iterator值会变化,注意for循环写法和it的更新
	ncolor.erase(remove(ncolor.begin(), ncolor.end(), make_pair(5,11)), ncolor.end());
	cout<<"删除元素(5,11):"<<endl;
	for(auto &p:ncolor) {
		cout<<p.first<<" "<<p.second<<endl;
	}
	cout<<"删除0:"<<endl;
	vector<pair<int, int>>::iterator it;
	for(it=ncolor.begin(); it!=ncolor.end();) {
		if((*it).first==0||(*it).second==0) {
			it=ncolor.erase(it);
		}else {
			it++;
		}
	}
	//几种遍历输出的写法
	for(it=ncolor.begin(); it!=ncolor.end(); it++) {
		cout<<(*it).first<<" "<<(*it).second<<endl;
	}
	cout<<endl;
	for(auto p:ncolor) {
		cout<<p.first<<" "<<p.second<<endl;
	}
	cout<<endl;
	for(auto &p:ncolor) {
		cout<<p.first<<" "<<p.second<<endl;
	}
	cout<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值