簡體   English   中英

如何檢查鍵是否存在於std :: map中,並在條件滿足的情況下獲取map :: iterator?

[英]How can I check if the key exists in a std::map and get the map::iterator in if condition?

我想在條件表達式中定義變量,以便變量范圍位於if子句內。 這樣很好

if (int* x = new int(123)) { }

當我嘗試對map :: iterator做類似的事情時,

if ((map<string, Property>::iterator it = props.find(PROP_NAME)) != props.end()) { it->do_something(); }

我收到error: expected primary-expression before 'it'

是什么讓int*map::iterator有所不同?

在這方面, int *map::iterator之間沒有區別。 int *map::iterator一起使用的周圍語義結構有所不同,這就是為什么一個編譯而另一個不編譯的原因。

if您可以選擇

if (declaration)

要么

if (expression)

聲明不是表達。 您不能將聲明用作較大表達式中的子表達式。 您不能將聲明用作顯式比較的一部分,而這正是您嘗試執行的操作。

例如,如果您嘗試使用int *做相同的事情,像這樣

if ((int* x = new int(123)) != NULL)

由於您的map::iterator代碼無法編譯的原因完全相同,因此代碼無法編譯。

你必須用

if (int* x = new int(123))

要么

int* x = new int(123);
if (x != NULL)

要么

int* x;
if ((x = new int(123)) != NULL)

如您在上面看到的, int *表現出與map::iterator完全相同的行為。

在您的示例中,無法在if s條件下聲明it並與props.end()進行比較。 您將不得不使用上述變體之一,即

map<string, Property>::iterator it = props.find(PROP_NAME);
if (it != props.end())

要么

map<string, Property>::iterator it;
if ((it = props.find(PROP_NAME)) != props.end())

選擇您喜歡的任何一個。

PS當然,正式的你也可以寫

if (map<string, Property>::iterator it = props.find(PROP_NAME))

但它沒有執行您想要的操作(不將迭代器的值與props.end()進行比較),並且可能根本無法編譯,因為迭代器類型可能無法轉換為bool

這是將其限制在范圍內的一種方法:

{
    auto it = props.find(PROP_NAME);
    if (it != props.end()) {
       it->do_something();
    }
}

當然,從技術上講,此范圍不是“如果范圍”,但對於所有實際意圖和目的也應同樣有效。

正如AndreyT已經解釋 (+1)一樣,聲明不能超越() ,您未將其用於int已將其用於迭代器。

映射迭代器包含firstsecond ,分別指向鍵和值。 要訪問該值的成員,請使用it->second.do_Something()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM