我正在编写一个程序,该程序读取电影及其等级的文本文件

电影.txt

7
Happy Feet
4
Happy Feet
5
Pirates of the Caribbean
3
Happy Feet
4
Pirates of the Caribbean
4
Flags of our Fathers
5
Gigli
1


第一个值(7)用于for循环,这是一个赋值,因此我无法更改任何内容。

我的任务是使用一张或多张地图来存储电影,评论计数(电影被评论多少次,例如,“快乐的脚”被评论3次)以及平均评论得分。
我怀疑我可以使用多图来完成此操作,但是我找不到类似的示例,因此我打算使用嵌套图来完成。

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cctype>
#include <map>
using std::cout;
using std::endl;
using std::isspace;
using std::getline;
using std::string;
using std::ifstream;
using std::map;
#include "Map.h"

int main(){

    ifstream inStream;
    int number, rating;
    string name;

    map<int, int> movieMap;
    map<string, map<int, int>> reviewMap;


    inStream.open("movies.txt");
    inStream >> number;
    inStream.ignore();

    for (int count = 0; count < number; count++){
        getline(inStream, name);
        inStream >> rating;
        inStream.ignore();
        ++reviewMap[name][rating];

    }


    std::map<int, int>::iterator itr1;
    std::map<string, map<int, int>>::iterator itr2;
    for (itr2 = reviewMap.begin(); itr2 != reviewMap.end(); itr2++)
    {

        std::cout << "\n " << itr2->first << endl;

        for (itr1 = itr2->second.begin(); itr1 != itr2->second.end(); itr1++)
        {
            std::cout <<  "\n" <<  itr1->first << endl;
        }
    }



    system("pause");
    return(0);


因此,目前我的代码正在按需要存储电影名称,但它会将我的评论计数和评论分数存储为单独的值。

例如,当我cout itr1->second表示“快乐的脚”时,我得到2个值2和1,其中我希望1的值是3,并且评论分数被存储为单独的值,但是仅当它们是唯一的时,所以“快乐的脚”就有2个值存储4和5,我想要1的值13(此值最终将是平均值,到达该值时,我将越过该桥)。

我不是在寻找完整的解决方案,而只是在朝着正确的方向发展。

最佳答案

一个简单的地图就可以满足您的需求。

从数据结构开始:

struct Rating
{
    int number;
    int totalRating;
};

map<string, Rating> reviewMap;


然后,您只需要保持总计即可。由此,您可以计算平均评分。

关于c++ - 具有2个值的STL映射,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28756203/

10-13 08:13