JTK
JTK

Reputation: 1519

STL map with 2 values

I'm writing a program that reads in a textfile of movies and their ratings

movies.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

The first value (7) is for a for loop, this is an assignment so I can't change anything.

My task is to use a map or multiple maps to store the movies, the review count(how many times a movie is reviewed, e.g. 3 for Happy Feet) and the average review score. I suspect I can use a multimap to accomplish this, but I can't find a similar example, so I've gone about doing it with a nested map.

#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);

So at the moment what my code is storing the movie name as I want, but it's storing my review count and my review scores as separate values.

For instance when I cout itr1->second for Happy Feet I get 2 values, 2 and 1, where I want 1 value of 3 and the review scores are been stored as separate values, but only when they are unique, so Happy Feet has 2 values stored, 4 and 5, where I want 1 value of 13(this value will eventually have to be an average, I'll cross that bridge when I come to it).

I'm not looking for a complete solution, just a pointer in the right direction.

Upvotes: 0

Views: 885

Answers (1)

Jamerson
Jamerson

Reputation: 484

A simple map will suffice for your needs.

Start with the data structure:

struct Rating
{
    int number;
    int totalRating;
};

map<string, Rating> reviewMap;

You then just need to keep running totals. From this, you can compute the average rating.

Upvotes: 1

Related Questions