2011-12-05 23 views
2

我正在爲引擎寫一個圖像處理程序。到目前爲止,它非常好(我認爲),但我需要幫助刪除圖像。我有vector s的經驗,但沒有map s的經驗。std :: map幫助圖像處理程序類

所述的圖像處理程序具有的std ::地圖,其具有2個元件:

std::map<std::string, SDL_Surface*> image_list_; 
std::map<std::string, SDL_Surface*>::iterator it; 

然後我有2種方法在我ImageHandler類:

void AddImage(std::string/*file_name*/); 
void DeleteImage(std::string/*file_name*/); 

以下是這2種方法的膽:

bool ImageHandler::AddImage(std::string file_name) 
{ 
    SDL_Surface* temp = NULL; 
    if ((temp = Image::Load(file_name)) == NULL) 
     return false; 
    image_list_.insert(std::pair<std::string, SDL_Surface*>(file_name, temp)); 
    SDL_FreeSurface(temp); 
    return true; 
} 

bool ImageHandler::DeleteImage(std::string file_name) 
{ 
    if (image_list_.empty()) return; 
    it = image_list_.find(file_name); 
    if (!it) return false; 
    image_list_.erase(it); 
    return true; 
} 

我還沒有編譯此代碼,所以我不知道任何語法錯誤。如果有的話,你可以看看那些。

我想我DeleteImage方法將從map刪除,但要避免內存泄漏,當加載圖像,我需要做到這一點:

SDL_FreeSurface(SDL_Surface*); 

所以我覺得我需要訪問迭代器的元素在特定的地圖索引處。我到目前爲止做得對嗎?我該如何做到這一點?

+0

SDL_FreeSurface(IT->第二); image_list_.erase(它); – Jagannath

回答

1

像這樣:

bool ImageHandler::DeleteImage(std::string const & file_name) 
{ 
    if ((it = image_list_.find(file_name)) == image_list_.end()) 
    { 
    return false; 
    } 

    SDL_FreeSurface(it->second); 
    image_list_.erase(it); 
    return true; 
} 
+0

我有一個問題,我將如何獲得地圖的第二個元素像索引像the_map_ [0] .second? – evolon696

+0

@sikesusmc:我不明白這個問題。地圖沒有「索引」,相反,他們有「鍵」。而'm [「hello」]'已經是鍵名爲「hello」的條目的*映射值*。 (或者,'m.find(「hello」) - > second',假設元素存在。) –

+0

哦。我如何獲得一個地圖的第二個元素只是一個數字?像數組或其他東西。不要映射使用[]運營商 – evolon696

1

是的,你說得對,你會做

SDL_FreeSurface(it->second); 

之前,你從地圖上抹掉它。

這將使功能:

bool ImageHandler::DeleteImage(std::string file_name) 
{ 
    if (image_list_.empty()) return; 
    it = image_list_.find(file_name); 
    if (!it) return false; 
    SDL_FreeSurface(it->second); 
    image_list_.erase(it); 
    return true; 
}