2013-10-30 65 views
0

地圖我有地圖的形式map<key1, map<key2, value> >的:檢查一個元素是否存在或不內地圖

例如: 我存儲在2-d座標的強度值(X, y)在以下地圖中:

map<int, map<int, double> > intensityValue; 

現在,我想檢查座標(x,y)處的強度值是否存在於此地圖中。 的一種方式,我知道是檢查:

if(intensityvalue[x][y] >=0) 
在這種情況下

,如果intensityValue[x][y]沒有在地圖中查看它會自動在地圖我不想插入intensityValue[x][y]後存在,那麼。

請建議一個有效的方法,以便我可以檢查intensityValue[x][y]是否已經存在於地圖中,而沒有將其插入到地圖中。

+4

['std :: map :: find'](http://en.cppreference.com/w/cpp/container/map)? – jrok

回答

4

可以一起使用std::map::find具有短路評價:

bool foundXY = instensityValue.find(x) != intensityValue.end() && 
       intensityValue[x].find(y) != intensityValue[x].end(); 

或:

bool foundXY = instensityValue.count(x) && intensityValue[x].count(y) 
+0

應該使用'count()'作爲y值檢查。 – JaredC

+0

@JaredC這是一個選項。因爲結果只能是0或1,所以我覺得'計數'對於地圖有點直觀,但我會添加選項。 – juanchopanza

+0

我認爲'count'和'find'具有相同的複雜性,應該可能具有相同的性能?或者我錯了? –

1

編寫一個簡短的功能,以確保調用地圖查找的最小數量。

bool hasIntensity(int x, int y) 
{ 
    map<int, map<int, double> >::const_iterator i = intensityValue.find(x); 
    if (i == intensityValue.end()) return false; 
    map<int, double>::const_iterator j = i->second.find(y); 
    return j != (i->second.end()); 
} 

如果你想在找到元素,以獲得實際價值,只是利用j->second

+1

這應該可能會返回迭代器而不是bool。這樣,您實際上可以用所發現的值做些事情,而不必再次進行地圖查找。 – Cogwheel

+0

當然,但應該仔細處理返回的迭代器以避免訪問失效的迭代器。 – timrau

+0

@timrau就像我們需要用'find'返回的迭代器一樣:) :) – jrok

0

這是有點難看,但應太:(使用C++ 11)

std::map<int, std::map<int, double> > intensityValue; 
int x,y; 
auto it = std::find_if(intensityValue.begin(), 
        intensityValue.end(), 
        [x,y](const std::pair<int, std::map<int, double>>& p){ 
         return p.first==x && 
          p.second.find(y) !=p.second.end(); 
        } 
        ); 

    if(it != intensityValue.end()) 
    { 
     //Got it ! 
    } 
+0

不幸的是,它失去了'map :: find'和'map :: count'的對數複雜度的好處。 – juanchopanza

+0

@ juanchopanza是的,同意! – P0W

1

使用std::map::find

auto outerIt = intensityValue.find(x); 
if (outerIt != intensityValue.end()) { 
    auto innerIt = outerIt->find(y); 
    if (innerIt != outerIt->end()) { 
     // Do something with the found value 
     return; 
    } 
} 
// Didn't return, so it wasn't found 

這就是說,在我的經驗,使用對單個地圖這種東西比嵌套地圖更高效,更易於使用。它更適合於標準算法,並且不涉及幾乎一樣多的樹導航。

template <typename T, typename U, typename V> 
using map2d = std::map<std::pair<T, U>, V>; 

int main() { 
    map2d<int, int, double> myMap { 
     {{3, 4}, 808.14f}, 
     {{1, 2}, 333.33f} 
    }; 
    auto it = myMap.find({3, 4}); 
    if (it != myMap.end()) { 
     std::cout << it->second << std::endl; 
    } 
} 
+0

+1使用一對映射代替 –

+0

@Cogwheel:我故意使用了嵌套映射,因爲在後期階段,我需要該行的所有點針對特定的'x'值,其強度值被設置,即intensityValue [x] [* ],這將很難找到使用這種方法(我認爲如此,不知道);) – techbull