Yotam
Yotam

Reputation: 10685

accessing map elements increase it's allocated memory size

I have a map<vector<double>,double> element in my code named EU.

I have noticed that the memory usage by my code tends to accumulate until I have used the entire available memory on my machine (going from ~200 MB to ~ 4GB). commenting out stuff in my code I have come to the conclusion that a line that access an element in this map is the one that, one commented out, prevent the memory usage increase. I access the value using []operator and I thought that this might be because the double values are not exactly the same as those in the map. I then searched for a case where this might be:

std::map<vector<double>,double>::iterator mit = EU.find(s);     
if (mit == EU.end()){
  for (int i = 0; i < 3; i++){
    O.w(s[i]);
  }
  cin.ignore();
}

Here O.w(s[i]) is a function In I class I have created to display stuff on screen/write to hard disk. In this case it is simply printf("%0.10f\n",s[i]) and I use cin.ignore() just to stop the program so I could check the output. Which also cause the increase in memory usage. Why is that so and how can I prevent this?

Thanks.

Upvotes: 1

Views: 358

Answers (1)

K-ballo
K-ballo

Reputation: 81349

When you access an element in a std::map, if the index has no associate value then a new element is created. So each time you access the map with a new key a new node is created to hold both the new std::vector< double > key and double value.

Upvotes: 3

Related Questions