算法入门 -- STL 入门学习map
map用于存储健值对的形式的数据。一般是int和string的键值类型,也可和结构体结合。
常见键值对
插入数据一般有三种方法,结合pair,value_type和数组形式的插入。
//
// Created by 29273 on 2021-03-22.
//
#include "bits/stdc++.h"
using namespace std;
int main() {
map<int, string> mapA;
// 结合value_type插入数据
mapA.insert(map<int, string>::value_type(1, "tom"));
mapA.insert(map<int, string>::value_type(2, "tony"));
mapA.insert(map<int, string>::value_type(3, "tk"));
// 结合pair插入数据
mapA.insert(pair<int, string>(4, "good"));
mapA.insert(pair<int, string>(5, "god"));
mapA.insert(pair<int, string>(6, "better"));
// 数组的形式
mapA[7] = "whatever";
// while 循环遍历
map<int, string>::iterator iter1 = mapA.begin();
while (iter1 != mapA.end()) {
cout << " " << iter1->first << " " << iter1->second << endl;
iter1++;
}
map<int, string>::iterator iter2 = mapA.begin();
// for 循环遍历
for (; iter2 != mapA.end(); iter2++) {
cout << " " << iter2->second << " " << iter2->first << endl;
}
return 0;
}
与结构体结合
//
// Created by 29273 on 2021-03-22.
//
#include "bits/stdc++.h"
using namespace std;
struct stu {
string name;
int age;
stu(string name, int age) {
this->name = name;
this->age = age;
}
};
int main() {
map<int, string> mapA;
map<int, stu> mapB;
mapB.insert(map<int, stu>::value_type(1, stu("area1", 3)));
mapB.insert(map<int, stu>::value_type(2, stu("area2", 3)));
mapB.insert(map<int, stu>::value_type(3, stu("area3", 3)));
map<int, stu>::iterator iter3 = mapB.begin();
for (; iter3 != mapB.end(); ++iter3) {
cout << iter3->first << " " << iter3->second.name << " " << iter3->second.age << endl;
}
return 0;
}

浙公网安备 33010602011771号