-2

std::map ストレージ内の要素が設定されているかどうかを調べる方法は? 例:

#include <map>
#include <string>

using namespace std;

map<string, FOO_class> storage;

storage["foo_el"] = FOO_class();

のようなものはありif (storage.isset("foo_el"))ますか?

4

4 に答える 4

5

試してみてくださいstorage.find("foo_el") != storage.end();

于 2013-08-25T14:37:14.750 に答える
1

std::map 演算子 [] は厄介です: 存在しない場合はエントリを作成し、最初に map::find を持ちます。

挿入または変更する場合

std::pair<map::iterator, bool> insert = map.insert(map::value_type(a, b));
if( ! insert.second) {
   // Modify insert.first
}
于 2013-08-25T14:44:17.370 に答える
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';
}
于 2013-08-25T14:55:28.200 に答える