今天遇到 second 的,分析代码,查 c++ map 手册,才知道second为何意。
/* 示例:*/
#include <iostream> #include <map> int main() { std::map<int, float> num_map; num_map[4] = 4.13; num_map[9] = 9.24; num_map[1] = 1.09; // 调用 map.begin() 与 map.end() for (auto it = num_map.begin(); it != num_map.end(); ++it) { std::cout << it->first << ", " << it->second << '\n'; } }
输出:
1, 1.09 4, 4.13 9, 9.24
简单理解:sencod 为 map 第二个元素。
/* 使用定制比较函数的示例: */
#include <cmath> #include <iostream> #include <map> struct Point { double x, y; }; // 比较二个 Pointer 指针的 x 坐标 struct PointCmp { bool operator()(const Point *lhs, const Point *rhs) const { return lhs->x < rhs->x; } }; int main() { // 注意尽管 x 坐标乱序,亦将按照递增的 x 坐标迭代 map Point points[3] = { {2, 0}, {1, 0}, {3, 0} }; // mag 是发送结点地址到其在 x-y 平面中长度的 map // 尽管键为指向 Point 的指针,我们希望按照点的 x 坐标而非点的地址为 map 赋序。 // 通过用 PointCmp 类的比较方法进行。 std::map<Point *, double, PointCmp> mag({ { points, 2 }, { points + 1, 1 }, { points + 2, 3 } }); // 从 0 到长度更改每个 y 坐标 for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; // 指向 Point 的指针 cur->y = mag[cur]; // 亦能用 cur->y = iter->second; } // 更新并打印每个点的长度 for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << iter->second << '\n'; } // 以基于范围的 for 循环重复上述内容 for(auto i : mag) { auto cur = i.first; cur->y = i.second; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << mag[cur] << '\n'; // 注意与上述 std::cout << iter->second << '\n'; 相反, // std::cout << i.second << '\n'; 将不打印更新的长度 } }
输出:
The magnitude of (1, 1) is 1.41421 The magnitude of (2, 2) is 2.82843 The magnitude of (3, 3) is 4.24264 The magnitude of (1, 1.41421) is 1.73205 The magnitude of (2, 2.82843) is 3.4641 The magnitude of (3, 4.24264) is 5.19615