我有一个 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);
- 这也会导致更少的内存分配,可能会加快速度。取决于您的计算是否昂贵以及您是否只能执行一次。
但是,我看不到 helperMap
比 bins
大得多 - 您确定这是问题所在吗?
关于c++ - std::map 使用大量内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312390/