sstream().map()不为空添加
时间: 2023-11-05 07:21:53 浏览: 75
C语言头文件 SSTREAM
5星 · 资源好评率100%
要在sstream中使用map,您需要先将字符串分割成单词,并将其添加到map中。以下是一种实现的方法:
```cpp
#include <string>
#include <sstream>
#include <map>
#include <iostream>
using namespace std;
int main() {
string str = "AA BB CC B 1 123";
istringstream stream(str);
string word;
map<string, int> wordCount;
while (stream >> word) {
wordCount[word]++;
}
// 检查map是否为空,如果为空则添加一个元素
if (wordCount.empty()) {
wordCount["default"] = 1;
}
for (const auto& pair : wordCount) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
```
这段代码将字符串`str`分割为单词,并使用map `wordCount` 存储每个单词的出现次数。然后,我们检查map是否为空,如果为空,则添加一个名为"default"的元素。最后,我们遍历map并输出每个单词及其出现次数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [C++ 基础知识:iostream/fstream/sstream以及std容器算法](https://blog.csdn.net/qq_32460819/article/details/119989971)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [C++头文件sstream笔试常见用法](https://blog.csdn.net/zhendong825/article/details/124955668)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文