我正在尝试通过使用旧的 C++ 代码并尝试将它们转换来练习我的 java 技能。所以我下面有使用 std::map 的代码(如下所示):
#include <map>
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char ** argv)
{
string ifile = argv[1];
ifstream icookie {ifile};
ofstream ocookie {"ocookie.txt",ios::out};
string Lines;
map<string,int>CookieMap;
while(getline(icookie,Lines))
{
CookieMap[Lines]++;
}
for (auto it : CookieMap)
{
cout << it.first << " " << it.second << endl;
}
return 0;
}
代码正在读取文件 ocookie.txt,其中包含:
chocolate
snickerdoodle
vanilla
chocolate
vanilla
sugar
vanilla
输出应该是:
chocolate 2
snickerdoodle 1
vanilla 3
sugar 1
我只是对如何像 java 中那样执行 std::map 感到困惑,因为我不确定会有多少行。谢谢您,我们将不胜感激。
最佳答案
您应该检查how to read a file in java 。然后,您可以使用HashMap Class以获得这种行为。
关于java - 在 C++ 和 Java 中使用 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61420105/