2013-08-25 14 views
-2

如何確定std :: map存儲中的元素是否已設置? 例子:如果元素在C++ std :: map中設置?

#include <map> 
#include <string> 

using namespace std; 

map<string, FOO_class> storage; 

storage["foo_el"] = FOO_class(); 

有什麼樣if (storage.isset("foo_el"))

回答

5
if (storage.count("foo_el")) 

count()返回一個數字的出現容器內的項目,但映射只能有一個鍵。因此storage.count("foo_el")在物品存在時爲1,否則爲0。

5

嘗試storage.find("foo_el") != storage.end();

1

std :: map運算符[]是討厭的:它創建一個條目,如果它不存在,有一個map :: find第一個。

如果要插入或修改

std::pair<map::iterator, bool> insert = map.insert(map::value_type(a, b)); 
if(! insert.second) { 
    // Modify insert.first 
} 
0

您還可以插入一個新的鍵值對時檢查迭代器:

std::map<char,int> mymap; 
mymap.insert (std::pair<char,int>('a',100)); 
std::pair<std::map<char,int>::iterator,bool> ret; 
ret = mymap.insert (std::pair<char,int>('a',500)); 
if (ret.second==false) { 
    std::cout << "element is already existed"; 
    std::cout << " with a value of " << ret.first->second << '\n'; 
}