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混合使用的例子
- map不能排序,因为map内部用红黑树实现 ,已具有内部排序机制。
如果想map进行排序,可以先将map元素转换为vector里的pair元素, 然后根据map的key(pair的first)或者map的value(pair的second)排序。 - vector里删除元素,用erase()函数,它接受iterator类型参数。
- .begin(), .end()返回的都是iterator, 前闭后开。
- 遍历容器用的也是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;
}