c++ - std::map 使用大量内存

标签 c++ std

我有一个 bin 数组:

vector<vector<int> > bins

程序计算大量Term 类型的对象和相应的整数。每个 bin 对应一个 Term 对象,并且整数需要在 bin 中结束。我目前正在这样做:

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

问题是 map (我不再需要它)比 bin 结构需要更多的内存,这给程序带来了严重的限制。有没有更有效的方法来做到这一点?

最佳答案

我会分两步完成。循环一次,计算您需要多少个 bin,然后调用 bins.resize(numberYouWillNeed) - 然后再次循环,您只需要 bins[x]。 push_back(tempInt); - 这也会导致更少的内存分配,可能会加快速度。取决于您的计算是否昂贵以及您是否只能执行一次。

但是,我看不到 helperMapbins 大得多 - 您确定这是问题所在吗?

关于c++ - std::map 使用大量内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312390/

相关文章:

c++ - 参数包中的参数计数?是否有 C++0x 标准库函数呢?

c++ - 是否有用于 C++ 的 Lua 表迭代器包装器?

C++ RFC3339 时间戳与毫秒使用 std::chrono

c++ - libstdc++.so.6 : version GLIBCXX_3. 4.20 未找到

c++ - 使用 std::bind 将函数传递给函数

c++ - 具有共享继承的 C++ 中的多态性

c++ - FCFS调度算法中按到达时间排序

c++ - 程序似乎跳过了 'if' 语句

c++ - 你能阻止 std::regex 在无效表达式上抛出异常吗?

c++ - 附加标准字符串时出现 bad_alloc 异常