如何在std::map结构中将指定字母替换为其他字母
C++ 嵌套结构map的全局字符替换方案
核心注意点
std::map 属于有序关联容器,其键值为const只读类型,不支持直接修改:直接修改键会破坏容器内部的排序规则,触发未定义行为。如果需要对键中的字符做替换,需要通过「新建替换后的键值对→整体替换原map」的方式实现;如果仅需要修改value中存储的字符串,直接遍历修改即可。
完整实现(同时替换所有键、值中的e为E)
推荐用临时map转存的方案,无需处理迭代器失效问题,实现更稳妥:
#include <map> #include <vector> #include <string> #include <algorithm> int main() { // 原始map结构 std::map<std::string, std::vector<std::string>> myMap; myMap["test"] = {"test1,test2,test3"}; myMap["test2"] = {"test21", "test22"}; // 临时map存储替换后的结果 std::map<std::string, std::vector<std::string>> newMap; for (const auto& entry : myMap) { // 替换键中的字符 std::string new_key = entry.first; std::replace(new_key.begin(), new_key.end(), 'e', 'E'); // 替换value中vector每个字符串的字符 std::vector<std::string> new_vec; new_vec.reserve(entry.second.size()); for (const auto& str : entry.second) { std::string new_str = str; std::replace(new_str.begin(), new_str.end(), 'e', 'E'); new_vec.emplace_back(std::move(new_str)); } newMap.emplace(std::move(new_key), std::move(new_vec)); } // 用替换后的内容覆盖原map myMap.swap(newMap); return 0; }
简化实现(仅替换值中的字符,不需要修改键)
如果不需要改动map的键,可以直接遍历修改value,无需新建临时map:
for (auto& entry : myMap) { for (auto& str : entry.second) { std::replace(str.begin(), str.end(), 'e', 'E'); } }
内容的提问来源于stack exchange,提问作者inver1123a
相关产品推荐
相关产品推荐

