You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将两个vector数据存入unordered_map时出错,求sortPeople函数修正方案

问题分析与修正

你的代码存在多处语法和逻辑错误,无法正确实现“按身高降序排列名字”的需求,具体问题如下:

  • 循环逻辑完全错误:嵌套遍历names和heights会让每个名字和每个身高强行配对,破坏了两个vector原本的一一对应关系。
  • 容器操作类型不匹配:
    • mp[heights].push_back(names)有两处错误:一是heights是vector类型,而unordered_map的键是int,类型不兼容;二是mp的value是string类型,不能用push_back插入整个vector。
  • 遍历写法错误:for (itr : mp)里的itr未声明类型,且mp.second属于语法错误,正确写法是itr.second来访问键值对的value。
  • 无序容器误用:unordered_map本身是无序的,即便数据存入正确,遍历结果也无法保证按身高降序排列,不符合需求。
  • 重复排序无意义:在循环内部多次调用sort(heights.rbegin(), heights.rend()),既浪费性能,还会打乱names和heights的原始对应关系。

修正后的代码实现

方案一:用pair存储对应关系后排序

先建立身高与名字的一一配对,再按身高降序排序,最后提取名字:

#include <vector>
#include <string>
#include <algorithm>

vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
    vector<string> result;
    vector<pair<int, string>> people;
    // 建立身高与名字的对应关系
    for (int i = 0; i < names.size(); ++i) {
        people.emplace_back(heights[i], names[i]);
    }
    // 按身高降序排序
    sort(people.rbegin(), people.rend());
    // 提取排序后的名字
    for (auto& p : people) {
        result.push_back(p.second);
    }
    return result;
}

方案二:用降序map实现

利用map的有序性,指定降序规则存储键值对,直接遍历得到排序结果:

#include <vector>
#include <string>
#include <map>

vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
    vector<string> result;
    // 指定map按键(身高)降序排列
    map<int, string, greater<int>> mp;
    for (int i = 0; i < names.size(); ++i) {
        mp[heights[i]] = names[i];
    }
    // 遍历map即可得到降序的名字
    for (auto& pair : mp) {
        result.push_back(pair.second);
    }
    return result;
}

注:如果存在相同身高的情况,map会覆盖之前的名字;若需要保留所有重复身高的名字,优先选择方案一并调整排序逻辑即可。

内容的提问来源于stack exchange,提问作者Rahul Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:35:16