如何使用range-based for循环遍历map值并完成数值比较操作
问题1:map按值排序后使用range-based for遍历的实现
- C++的
std::map底层是按键默认排序的红黑树,本身不支持直接按值排序,因此你无法直接对原生map用range-based for得到按值排序的遍历序列。 - 你现有的代码逻辑是正确的第一步:可以先通过range-based for把map的所有值/完整pair元素提取到vector中,对vector按值排序后,就能用range-based for遍历排序后的序列,完成大小判断逻辑:
// 示例实现 std::map<int, int> M = {{1,5}, {2,2}, {3,7}, {4,1}}; std::vector<std::pair<int, int>> temp_vec; // 提取map元素到vector for (auto& it : M) { temp_vec.push_back(it); } // 按value升序排序 std::sort(temp_vec.begin(), temp_vec.end(), [](const auto& a, const auto& b) { return a.second < b.second; }); // 排序后遍历做大小判断 int threshold = 3; for (auto& elem : temp_vec) { if (elem.second > threshold) { // 你的业务逻辑 } }
问题2:存储pair的vector通过range-based for访问second成员做比较
完全可以实现,range-based for遍历拿到的元素就是vector存储的pair对象,直接取second成员即可完成和固定值、其他元素的大小比对,示例如下:
std::vector<std::pair<std::string, int>> score_vec = {{"张三", 89}, {"李四", 76}, {"王五", 95}}; // 和固定值比较,筛选分数高于80的条目 for (auto& item : score_vec) { if (item.second > 80) { std::cout << item.first << " 分数达标\n"; } } // 元素之间互相比对,查找最高分 int max_score = 0; for (auto& item : score_vec) { if (item.second > max_score) { max_score = item.second; } }
内容的提问来源于stack exchange,提问作者user17459745
相关产品推荐
相关产品推荐

