0

Hi so I have a homework assignment and have it all done except for the last requirement. We're pulling in data from a txt file and several of the box office values are 0. Instead of returning the first instance of 0, we are to return the last instance of 0. Here's a snippet of code:

long long worldBoxOffice = movie.getWorldBoxOffice();
movieMap.insert(pair<long long, Movie>(worldBoxOffice, movie));

So after inserting the pair into the map, what is it that I should be doing? Would it be overloading the [] operator? Kinda confused so any help is appreciated. I didn't post more code because I'm not looking for code, just a push in the right direction as to how to go about it. Thanks.

Note: we have to use maps, not allowed to use multi maps, etc.

MPelletier
  • 16,256
  • 15
  • 86
  • 137

2 Answers2

2

Maybe I am misunderstanding but if you just use operator [] instead to assign to the map when you read in your data you will end up with the last 0 instance that you read in, like this trivial example:

#include <iostream>
#include <map>

int main()
{
   std::map<int,int>
    m ;

    m[0] = 1 ;

    std::cout << m[0] << std::endl ;

    m[1] = 2 ;

    m[0] = 3 ;

    std::cout << m[0] << std::endl ;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

As insert doesn't replace existing keys, you should not be using it in the first place. Nothing after such an (ineffective) insert will get your data back.

You can use the [] operator: movieMap[worldBoxOffice] = movie; or do the insertions in reverse order - read the file backwards.

Community
  • 1
  • 1
aib
  • 45,516
  • 10
  • 73
  • 79