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

C++中将带-开头键的字符串按<key,value>格式存入map的问题

问题根因
  • 代码处理最后剩余的参数字符串-peak时,调用s.find_first_of(' ')未匹配到空格,返回string::npos。由于string::npos是无符号类型的最大值,加1后溢出为0,s.substr(0)直接返回了整个-peak字符串,导致值被错误赋值为键本身。
  • 原逻辑未对「键后无空格即无对应值」的场景做特殊判断,默认所有键后都存在可提取的值,存在边界处理漏洞。
修复后完整代码
#include <iostream>
#include <string>
#include <map>

using namespace std;

int main() {
    string s = "parrot -color green -peak";
    char sep = '-';
    map<string, string> clArgs;
    
    size_t sep_pos = s.find_first_of(sep);
    string executable_name = s.substr(0, sep_pos);
    cout << "exec name = " << executable_name << endl;
    
    if (sep_pos != string::npos) {
        s.erase(0, sep_pos);
    } else {
        s = "";
    }
    cout << "s = " << s << endl;
    
    size_t pos;
    while ((pos = s.find_first_of(sep, 1)) != string::npos)
    {
        string keyVal = s.substr(0, pos);
        s = s.substr(pos);
        
        string key, value;
        size_t space_pos = keyVal.find_first_of(' ');
        key = keyVal.substr(0, space_pos);
        if (space_pos != string::npos) {
            keyVal = keyVal.substr(space_pos + 1);
            value = keyVal.substr(0, keyVal.find_first_of(' '));
        } else {
            value = "";
        }
        clArgs[key] = value;
    }
    
    if (s.length() != 0)
    {
        size_t space_pos = s.find_first_of(' ');
        string key = s.substr(0, space_pos);
        string value = "";
        if (space_pos != string::npos) {
            value = s.substr(space_pos + 1);
        }
        clArgs[key] = value;
    }
    
    cout << "Printing key-value pairs ...\n";
    for (map<string, string>::iterator it = clArgs.begin(); it != clArgs.end(); it++)
    {
        cout << "(key = " << it->first << ", value = " << it->second << ")\n";
    }
    return 0;
}
运行结果

修复后输出完全符合预期:

exec name = parrot 
s = -color green -peak
Printing key-value pairs ...
(key = -color, value = green)
(key = -peak, value = )

内容的提问来源于stack exchange,提问作者Amith Kotian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 15:39:01