我有一个vector<string>
需要处理的大型邮件(大小约为100万):
stringstream numStr;
cout << "before loop" << endl;
for(unsigned int i = 0; i < numList.size(); i++) {
cout << i << ": " << ((NORM_MAX - NORM_MIN) * (atoi(numList[i].c_str()) - min)) / (max - min) + NORM_MIN << endl;
int number = ((NORM_MAX - NORM_MIN) * (atoi(numList[i].c_str()) - min)) / (max - min) + NORM_MIN;
numStr << number;
numList[i] = numStr.str();
}
但是,程序在达到36691〜36693时崩溃
(snip)
36689: 288
36690: 264
36691: 245
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
我该怎么做才能找出造成此问题的原因?
正如您的代码现在一样,您将stringstream
在循环外部,这意味着您将一遍又一遍地不断向现有流的末尾添加新数字,然后在每次循环迭代中存储整个列表:
numList[i] = "... 288"
numList[i+1] = "... 288 264"
numList[i+2] = "... 288 264 245"
等等...
因此,是的,如果分配的单号非常大,则最终将耗尽其内存,尝试分配其中的单 号具有格式化string
的整个数字列表numList.size()
。
你可能打算把stringstream
内环路代替,使每一个迭代格式和存储单 int
中的每个值numList
槽:
cout << "before loop" << endl;
for(unsigned int i = 0; i < numList.size(); i++) {
int number = ((NORM_MAX - NORM_MIN) * (atoi(numList[i].c_str()) - min)) / (max - min) + NORM_MIN;
cout << i << ": " << number << endl;
stringstream numStr;
numStr << number;
numList[i] = numStr.str();
}
numList[i] = "288"
numList[i+1] = "264"
numList[i+2] = "245"
等等...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句