map的一些常用方法
对于map来说,底层实现是红黑树,在插入的时候就会按照key值来排序,所以如果是插入的自定义数据类型
那么就需要写仿函数,重载小括号来实现插入,对于自定义排序规则
也要通过仿函数以及重载小括号来实现想要的排序。
multimap相对于map来说可以插入重复的key值,与set相同的是,map如果插入的数据的key是一样的就会插入失败,不同点是通过map[key] = value;
这种方法来实现的插入,如果存在key值则更新value
,如果不存在key值则插入key-value
键值对。
void printfMap(const map<string,int> &m) {
for (map<string, int>::const_iterator it = m.begin(); it != m.end(); it++) {
cout << "string: " << it->first << " int: " << it->second <<endl;
}
cout << endl;
}
int main() {
map<string, int> mp; //默认构造
map<string, int> mp01(mp); //拷贝构造
mp01 = mp; //赋值
mp.insert(make_pair("小明", 15)); //插入make_pair;
mp["小明"] = 16; //这个也是插入,利用key更新value,如果有key则更新value,没有key则重新插入key和value。
cout << mp["小明"] << endl; //可以利用key来访问到value;
printfMap(mp);
mp.erase("小芳"); //删除key值对应的数据
mp.erase(mp.begin()); //删除迭代器对应的数据
mp.clear(); //清空map容器。
if (mp.find("小芳") != mp.end()) { //按key值查找,找到了就返回迭代器的位置,没找到就返回end()。
cout << "存在" << endl;
}
else cout << "不存在,没找到" << endl;
mp.count("小芳"); //统计key值有多少个
mp.size(); //返回容器中元素的数目
mp.empty(); //判空操作
mp.swap(mp01); //交换mp和mp01的数据
system("pause");
return 0;
}
map 排序
class Dog {
public:
Dog(string name, int age) {
this->dog_name = name;
this->dog_age = age;
}
string dog_name;
int dog_age;
};
class UpSortForDogAge { //按照狗的年龄进行升序排列
public:
bool operator()(Dog d1,Dog d2) const {
return d1.dog_age < d2.dog_age;
}
};
class DownSortMap { //实现按照key值逆序排序
public:
bool operator()(int val1,int val2) const{
return val1 > val2;
}
};
void printfMap(const map<int,int,DownSortMap> &m) {
for (map<int, int,DownSortMap>::const_iterator it = m.begin(); it != m.end(); it++) {
cout << "key: " << it->first << " value: " << it->second <<endl;
}
cout << endl;
}
void printfDogMap(const map<Dog, string, UpSortForDogAge>& m) {
for (map<Dog, string, UpSortForDogAge>::const_iterator it = m.begin(); it != m.end(); it++) {
cout << it->second << " 的 " << it->first.dog_name << "现在" << it->first.dog_age << "岁了!" << endl;
}
cout << endl;
}
int main() {
map<int, int,DownSortMap> mp;
mp.insert(make_pair(1, 10));
mp.insert(make_pair(2, 20));
printfMap(mp);
map<Dog, string, UpSortForDogAge> dog_map;
Dog d1("边牧", 15);
Dog d2("柯基", 3);
Dog d3("斗牛", 8);
Dog d4("泰迪", 2);
dog_map[d1] = "小a";
dog_map[d2] = "小b";
dog_map[d3] = "小c";
dog_map[d4] = "小d";
printfDogMap(dog_map);
system("pause");
return 0;
}
unordered_map
底层使用哈希实现的,具有很高的查找效率,对于unordered_multimap与unordered_map区别就是一个可以插入相同的key值一个不允许插入相同的key值。
int main() {
unordered_map<int, int> mp;
mp.insert(make_pair(2, 5)); //插入
mp[3] = 15; //插入
mp[3] = 16; //插入,如果不存在key就插入这个键值对,如果存在这个key就更新value这个值
mp.erase(3); //删除key对应的数据
if (mp.find(3) != mp.end()) { //查找key,存在返回key对应的迭代器位置,不存在返回end()位置。
cout << "找到了" << endl;
}
else cout << "没找到" << endl;
cout << mp[3] << endl; //取key对应的value值。
system("pause");
return 0;
}