我有一个文本文件,用于存储棒球运动员 ID 和运动员 rbi(击球次数)总数。 ids都是四位数,rbis的范围是60到110,长这样。
5554 102 87 63 90 5553 66 68 90 102 等等……
我编写了一些代码来将 ID 存储在一个集合中,计算文本文件中四个 rbi 总数的平均值,并将结果输出到控制台。我的家庭作业说我必须将玩家 ID 和 rbi 平均值存储到一对 map ,而不是一组。我以为我读到映射对的语法是
typedef pair<const Key, T> value_type;
但我无法用映射对重写这段代码。有什么想法吗?
#include <iostream>
#include <fstream>
#include <set>
using namespace std;
int main()
{
ifstream input("filepath\\*.txt");
multiset<int> values;
// Read data from file
for(unsigned int j = 1; j <= 4; j++)
{
int player;
(input >> player);
int rbi;
double total = 0.0;
double average = 0.0;
for(unsigned int i = 1; i <= 4; i++)
{
// Compute the average.
(input >> rbi);
values.insert(rbi);
total += rbi;
average = total/4;
}
//Output totals to console
cout << player;
cout << " " << average << endl;
}
system("Pause");
return 0;
}
最佳答案
我认为他们希望您将结果存储在 std::map 中。它是 C++ 中键值对的容器 (std::pair)。您可以使用以下语法将值插入 map :map[key] = value;
例如。
std::map<int, int> baseball_players;
for (...)
{
// Calculate average
baseball_players[player] = average;
}
关于C++ 使用文本文件中的数据存储映射对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16332581/