目录
举例:
#include <iostream>
#include <string>
#include <iomanip>
#include <map>
template<typename Map>
void print_map(Map& m) {
std::cout << '{';
for(auto& p: m)
std::cout << p.first << ':' << p.second << ' '; //first表示key, second表示value
std::cout << "}\n";
}
struct Point {double x,y;};
struct PointCmp {
bool operator()(const Point& lhs, const Point& rhs) const {
return lhs.x < rhs.x;
}
};
int main() {
// 默认构造函数
std::map<std::string, int> map1;
map1["something"] = 69;
map1["anything"] = 199;
map1["that thing"] = 50;
std::cout << "map1 = ";
print_map(map1);
// 范围构造
std::map<std::string, int> iter(map1.find("something"), map1.end());
std::cout << "\niter = ";
print_map(iter);
std::cout << "map1 = ";
print_map(map1);
// 复制构造函数
std::map<std::string, int> copied(map1); //复制之后,原对象还存在数据
std::cout << "\ncopied = ";
print_map(copied);
std::cout << "map1 = ";
print_map(map1);
// 移动构造函数
std::map<std::string, int> moved(std::move(map1)); //移动之后,原对象数据消失
std::cout << "\nmoved = ";
print_map(moved);
std::cout << "map1 = ";
print_map(map1);
// 初始化构造列表
const std::map<std::string, int> init {
{"this", 100},
{"can", 100},
{"be", 100},
{"const", 100},
};
std::cout << "\ninit = ";
print_map(init);
// 自定义键类选项1
// 使用比较构造
std::map<Point, double, PointCmp> mag = {
{{5, -12}, 13},
{{3, 4}, 5},
{{-8, -15}, 17}
};
for(auto p : mag)
std::cout << "The magnitude of {" << p.first.x
<< ", " << p.first.y << ") is "
<< p.second << "\n";
// 自定义键类选项1
// 使用lambda比较
auto cmpLambda = [&mag](const Point &lhs, const Point &rhs) { return mag[lhs] < mag[rhs]; };
std::map<Point, double, decltype(cmpLambda)> magy(cmpLambda);
// 插入各种元素的各种方法~
magy.insert(std::pair<Point, double> ({5, -12}, 13));
magy.insert({{3, 4}, 5});
magy.insert({Point{-8.0, -15.0}, 17});
std::cout << "\n";
for(auto p : magy)
std::cout << "The magnitude of (" << p.first.x
<< ", " << p.first.y << ") is "
<< p.second << "\n";
}
输出为:
map1 = {anything:199 something:69 that thing:50 }
iter = {anything:199 something:69 that thing:50 }
map1 = {anything:199 something:69 that thing:50 }
copied = {anything:199 something:69 that thing:50 }
map1 = {anything:199 something:69 that thing:50 }
moved = {anything:199 something:69 that thing:50 }
map1 = {}
init = {be:100 can:100 const:100 this:100 }
The magnitude of (-8, -15) is 17
The magnitude of (3, 4) is 5
The magnitude of (5, -12) is 13
The magnitude of (3, 4) is 5
The magnitude of (5, -12) is 13
The magnitude of (-8, -15) is 17
原文:https://www.cnblogs.com/hugechuanqi/p/10775898.html