1
我想問的是當queue.pop()被調用時內存釋放嗎? ,因爲在堆棧中我們只是遞增或遞減指針,但內存仍然沒有被釋放。pop()隊列中的內存浪費
問題是:WAP打印大日誌文件的最後n行。
我保存隊列中的行,然後當count> n時彈出行。
這是一個很好的編碼練習嗎?
如果不是可以做什麼來釋放內存?
我編碼是:
#include<iostream>
#include<queue>
#include<fstream>
using namespace std;
void lastN(char *fileName, int N)
{
queue<string> q;
int count=0;
string line;
ifstream mf(fileName);
if(mf.is_open())
{
while(!mf.eof())
{
getline(mf,line);
count++;
q.push(line);
if(count>N)q.pop();
}
mf.close();
}
else cout<<"cannot open file\n";
count=1;
while(q.size())
{
printf("line no %2d :: ",count++);
cout<<q.front()<<endl;
q.pop();
}
cout<<endl;
}
int main(void)
{
char *fileName="file.txt";
ofstream mf(fileName);
if(mf.is_open())
{
mf<<"line 0";
mf<<"line 1\nline 2\nline 3\nline 4\n\n\n";
mf.close();
}
else cout<<"cannot create file\n";
lastN(fileName,5);
getchar();
return 0;
}
謝謝。 你說過「隊列是按值保存字符串對象」。 你的意思是如果隊列持有指向對象的指針,那麼它將不會被釋放? –
是的,確切地說。如果隊列保持原始指針,則內存不會被釋放。但是使用智能指針也會釋放內存。 'std :: queue>'就你而言,這是一個不必要的開銷。 –
cdmh