出于某種原因,我需要多次遍歷影像,并且需要知道我處理了哪些像素點。
所以我使用 QVector 來存盤我每次處理過的像素點的位置,這樣我就可以用它來確定下一次迭代的時候。
例子如下。
QVector<int> passed;
for(int n = 0; n < 10; n ) { // Multiple traversals
for(int y = 0; y < height; y ) {
for(int x = 0; x < width; x ) {
if(......) { // Meeting certain conditions
if(!passed.contains(y*width x)) {
// do something
passed.append(y*width x);
}
}
}
}
}
我花了很多時間處理passed.contains()這一步!
你知道我如何優化搜索速度嗎?
或者有沒有更好的方法讓我更容易確定已處理的某些像素?
uj5u.com熱心網友回復:
用這個:
QVector<bool> passed(height * width, false);
for(int n = 0; n < 10; n ) { // Multiple traversals
for(int y = 0; y < height; y ) {
for(int x = 0; x < width; x ) {
if(......) { // Meeting certain conditions
int pos = y*width x;
if(!passed.at(pos)) {
// do something
passed[pos] = true;
}
}
}
}
}
或者也許您可以通過重新排序內部條件來獲得更快的速度。如果評估if(......)不是微不足道的,它可能會更快。但您必須確保此更改不會影響您的演算法。
QVector<bool> passed(height * width, false);
for(int n = 0; n < 10; n ) { // Multiple traversals
for(int y = 0; y < height; y ) {
for(int x = 0; x < width; x ) {
int pos = y*width x;
if(!passed.at(pos)) {
if(......) { // Meeting certain conditions
// do something
passed[pos] = true;
}
}
}
}
}
uj5u.com熱心網友回復:
QVector 中的元素是否必須按順序存盤?如果沒有,請嘗試 QSet 或 std::unordered_set。哈希在搜索時效果很好。
如果您必須按順序存盤這些索引,則有以下方法:
- 用串列替換向量,如 std::list<>,附加時速度更快
- 繼續使用 QVector 但呼叫 Reserve 以避免在追加時進行無用的復制
- 一種新的有序存盤方式:創建一個與影像大小相同的qvector,向量中的每個元素都記錄了這個元素的順序。例如,第 4 個元素是 32 表示第 4 個像素是第 33 個訪問過的像素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337945.html
