RobVerheyen
RobVerheyen

Reputation: 435

std::map using large amounts of memory

I have an array of bins:

vector<vector<int> > bins

The program calculates a large amount of object of the type Term and a corresponding integer. Every bin corresponds with a Term object, and the ints need to end up in the bins. I am currently doing this:

map<Term, int> helperMap;
int binNumber=0;
while(/*some condition*/)
     {
     Term temp;
     int tempInt;
     //Do some calculation to find temp & tempInt

     if (helperMap.find(temp)==helperMap.end())
          {
          vector<int> newBin;
          newBin.push_back(tempInt);
          bins.push_back(newBin);
          helperMap[temp] = binNumber;
          binNumber++;
          }

      else 
          {
          bins[helperMap.find(temp)->second].push_back(tempInt);
          }
      }

The problem is that the map (which I don't need anymore further on) requires much more memory than the bin structure, and this is putting serious constraints on the program. Is there any more efficient way to do this?

Upvotes: 1

Views: 116

Answers (1)

Salgar
Salgar

Reputation: 7795

I would do it in two steps. Spin through your loop once, calculate how many bins you're going to need, and call bins.resize(numberYouWillNeed) - Then spin through again and all you need is bins[x].push_back(tempInt); - This will result in far fewer memory allocations too, probably making this faster. Depending on whether your calculations are expensive and whether you can only do them once.

However, I can't see helperMap being enormously bigger than bins - are you sure that is the problem?

Upvotes: 1

Related Questions