2016-02-26 11 views
0

我將如何找到一個向量元素從它的參數與emplace_back 試圖分離線程然後從向量中刪除它設置一個一個找到的矢量的元素。從它的參數

std::vector<std::thread> vTimerThreads; 
void SetTimer(UINT ID, DWORD dwMilliseconds) 
{ 
    // timerThreadProc is my thread that handles my timers 
    vTimerThreads.emplace_back(timerThreadProc, ID, dwMilliseconds); 
} 
void DeleteTimer(UINT ID) 
{ 
    //Find thread by ID? 
    // thread.detach(); 
    // then delete 
} 

SetTimer(TIMER1, 5000); 
+1

您尚未在任何地方存儲「ID」,至少可以從矢量訪問的任何位置。 – chris

回答

1

如果你想要做一個簡單的線性搜索(這是有道理的,如果線程的數量並不大),你可以做

void DeleteTimer(UINT ID) 
{ 
    for(int i = 0; i < vTimerThreads.size(); i++) 
    if(vTimerThreads[i].get_id() == ID) 
    { 
     vTimerThreads.erase(vTimerThreads.begin()+i); 
     break; 
    } 
} 

如果你的線程數量很大,任意刪除像這樣很昂貴 - 在這種情況下,您可能需要考慮諸如forward_list而不是vector

+0

你剛剛重新實現了'std :: find_if'。 – chris

+0

是的,我不知道這個功能。謝謝你的提示。我會編輯答案。 –

+0

ID沒有標準::螺紋:: get_id() – ramafe

3

std::find_if聽起來像你想要什麼,如果你只是要刪除基於ID。

void DeleteTimer(std::thread::id ID) 
{ 
    std::vector<std::thread>::iterator itr = std::find_if(vTimerThreads.begin(), vTimerThreads.end(), [&](const std::thread& t) { return t.get_id() == ID; }); 
    if(itr != vTimerThreads.end()) 
     vTimerThreads.erase(itr); 
} 

我在這裏使用了lambda表達式,但沒有必要。

如果你想使用大量線程的,也許不同的數據結構會更適合你。你有沒有考慮過std :: set來加快搜索速度?也許即使是地圖或hash_map對你也有好處,其中id是關鍵?你可以把這些線程放到這些容器中,而不是使用emplace_back來移動語義而不用複製(因爲我懷疑是在激勵你使用emplace)。

時退房std::algorithm library雖然,有在那裏

編輯一些偉大的東西: 我的意見,一見OP說,ID其實也不是線程ID。除非我們能夠澄清我們打算搜索的std::vector<T>的T的哪個成員,否則不能提供明確的解決方案。

只要我做編輯,這裏是添加線程一個std ::地圖,而複製一些代碼。使用下面的代碼,通過std :: thread :: id或其他你想用作鍵的元素來找到一個元素是很簡單的,然後刪除它。

std::map<std::thread::id, std::thread> mapTimerThreads; 

void AddNewThreadToMap() 
{ 
    std::thread t; 
    mapTimerThreads[t.get_id()] = std::move(t); 
} 
+1

在擦除之前,您應該檢查'itr!= vTimerThreads.end()'。 – Jarod42

+0

@ Jarod42哦,天哪,我不能相信我離開了那個。謝謝你接受!我已經編輯了那個答案。 –