I have text file containing several numbers and string text. I would like to read text file into multimap. But don't know for sure whether my code is correctly done, because my code is crashing every time.
Sample text looks like:
7
Batman vs Superman
4
Batman vs Superman
5
Pirates of the Caribbean
3
Finding Dory
3
Batman vs Superman
4
Harry Potter and the Chamber of Secrets
5
Pirates of the Caribbean
4
Where number 7 - is quantity of movies, and other numbers are ratings of movies.
What's the benefit of using std::multimap and is it necessary? Using a struct:
1 2 3 4 5
struct MovieReview
{
std::string m_movieName;
int m_movieRating;
};
you could read off the first line of the file into a dummy string and then construct MovieReview instances from every 2 lines of the rest of the file and store these objects in a std::vector<MovieReview>
multimap<string, map<int, int>> mapReview;
this does not capture the layout of the data, try and match structs, containers to the arrangement of the data that you're working with. For example, here the string might correspond to the name of the film but what is supposed to be represented by the
#include <map>
#include <vector>
#include <string>
#include <fstream>
// key == name of film; mapped value == vector of ratings
using database = std::map< std::string, std::vector<int> > ;
database create_db_from( std::istream& istm )
{
database db ;
std::string film ;
int rating ;
// note: the >> std::ws at the end is to extract and discard the
// new line that would remain in the input buffer after istm >> rating
while( std::getline( istm, film ) && istm >> rating >> std::ws )
db[film].push_back(rating) ;
return db ;
}