C++如何用cin输入["eat", "tea", "tan", "ate", "nat", "bat"]
时间: 2024-01-15 22:19:49 浏览: 20
C++可以使用`cin`来输入字符串数组。以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> strs;
string str;
while (cin >> str) {
strs.push_back(str);
}
// 输出输入的字符串数组
for (const auto& s : strs) {
cout << s << " ";
}
cout << endl;
return 0;
}
```
运行这段代码,然后输入字符串数组`["eat", "tea", "tan", "ate", "nat", "bat"]`,按下回车键结束输入。程序会将输入的字符串数组存储在`strs`向量中,并输出该向量的内容。
相关问题
如何使用cin输入["eat", "tea", "tan", "ate", "nat", "bat"]
使用C++的标准输入流`cin`可以实现输入字符串列表["eat", "tea", "tan", "ate", "nat", "bat"]。下面是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> strs;
string str;
cout << "请输入字符串列表,以空格分隔:" << endl;
while (cin >> str) {
strs.push_back(str);
}
cout << "输入的字符串列表为:" << endl;
for (const auto& s : strs) {
cout << s << " ";
}
cout << endl;
return 0;
}
```
运行以上代码,你可以通过键盘输入字符串列表,以空格分隔。输入完成后,程序会将输入的字符串列表打印出来。
C++实现["eat", "tea", "tan", "ate", "nat", "bat"]输入
以下是C++实现给定字符串列表的字母异位词分组的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (string str : strs) {
string key = str;
sort(key.begin(), key.end()); // 将字符串按字母顺序排序作为分组的键
groups[key].push_back(str); // 将字符串添加到对应的分组中
}
vector<vector<string>> result;
for (auto it = groups.begin(); it != groups.end(); ++it) {
result.push_back(it->second); // 将每个分组添加到结果中
}
return result;
}
int main() {
vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector<vector<string>> result = groupAnagrams(strs);
for (vector<string> group : result) {
cout << "[";
for (int i = 0; i < group.size(); ++i) {
cout << "\"" << group[i] << "\"";
if (i < group.size() - 1) {
cout << ",";
}
}
cout << "]" << endl;
}
return 0;
}
```
输出结果为:
```
["bat"]
["nat","tan"]
["ate","eat","tea"]
```