我有下面的代碼,我想讓它工作得更好,速度更快。我想我應該改變擦除方法。有什麼想法嗎?我想我有內存泄漏,但我不知道要改變什麼。替代擦除功能C++更好的內存和時間節省
#include <iostream>
#include <unordered_map>
#include <string>
class DocumentStorage
{
class Document
{
public:
Document(std::string& title, std::string& content)
{
this->title = title;
this->content = content;
}
std::string title;
std::string content;
};
public:
void add(int id, std::string title, std::string content)
{
storage[id] = new Document(title, content);
}
void remove(int id, std::string& title, std::string& content)
{
std::unordered_map<int, Document*>::iterator it = storage.find(id);
Document* doc = it->second;
title = doc->title;
content = doc->content;
storage.erase(it);
}
void clear()
{
storage.clear();
}
private:
std::unordered_map<int, Document*> storage;
};
#ifndef RunTests
int main()
{
DocumentStorage storage;
storage.add(123456, "Hamlet", "Hamlet, Prince of Denmark.");
storage.add(123457, "Othello", "Othello, the Moore of Venice.");
std::string title, content;
storage.remove(123456, title, content);
std::cout << title << '\n';
std::cout << content;
storage.clear();
}
#endif
更快?你有沒有測量過這個函數是你應用程序中的瓶頸? –
我想讓代碼更快,我認爲問題出在代碼的那一部分。你有另一個想法嗎? –
那麼,你會得到一個'Document'對象來修改它,只是在之後立即清除它?誰擁有'文檔*'?除了'存儲'以外的東西是否有其參考? – Chad