如何通过映射将字符串替换为整数?C++代码实现求助
补全单词映射替换的C++压缩逻辑代码
需求说明
输入字符串,解析单词(保留标点)并存入vector;使用map建立单词与整数的映射,将重复出现的单词替换为对应整数,模拟文件压缩逻辑。例如输入one two one two three two,应输出one two 0 three 1。
用户现有代码
#include <iostream> #include <map> #include <vector> using namespace std; vector<string> getWords() { string word; vector<string> words; cin >> word; while (word != "$EOF$") { words.push_back(word); cin >> word; } return words; } int main() { map<string,int> abbr; string output = ""; int next=0; vector<string> words = getWords(); for (auto word:words) { if (abbr.find(word) == abbr.end()) { // put word to number mapping in map if new word // Output word if first time seen // Output number otherwise } } cout << output << endl; }
补全后的代码及解释
只需要在main函数的循环中补全核心逻辑即可,关键是区分首次出现和重复出现的单词,处理映射与输出:
int main() { map<string,int> abbr; string output = ""; int next=0; vector<string> words = getWords(); for (size_t i = 0; i < words.size(); ++i) { string word = words[i]; if (abbr.find(word) == abbr.end()) { // 首次出现的单词:建立映射,追加原单词到输出 abbr[word] = next; output += word; next++; } else { // 重复出现的单词:追加对应整数到输出 output += to_string(abbr[word]); } // 给非末尾元素添加空格,避免输出首尾多余空格 if (i != words.size() - 1) { output += " "; } } cout << output << endl; }
核心逻辑说明
- 映射建立:首次遇到单词时,将单词与当前
next值绑定存入map,next作为下一个新单词的编号,每次新增后自增 - 输出拼接:用索引循环替代范围循环,方便判断是否为最后一个元素,避免输出末尾多余空格
- 类型转换:通过
to_string()将整数转为字符串,实现输出内容的统一拼接
测试输入:
one two one two three two $EOF$
输出结果:
one two 0 three 1
内容的提问来源于stack exchange,提问作者dyinng
相关产品推荐
相关产品推荐

