2013-08-25 2 views
-2

std :: map 저장소에있는 요소가 설정되어 있는지 확인하는 방법은 무엇입니까? 예 : if (storage.isset("foo_el")) 같은 것이요소가 C++ std :: map에 설정된 경우?

#include <map> 
#include <string> 

using namespace std; 

map<string, FOO_class> storage; 

storage["foo_el"] = FOO_class(); 

있습니까?

답변

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

count()가의 발생 수를 반환합니다 컨테이너 내의 항목이지만지도에는 각 키가 하나만 나타날 수 있습니다. 따라서 storage.count("foo_el")은 항목이 있으면 1이고 그렇지 않으면 0입니다.

5

시도 storage.find("foo_el") != storage.end();

1

std :: map operator [] is not nasty : 항목이 없으면 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'; 
} 
관련 문제