2016-04-06 10 views
0

私はこのコードを持っています。実際にマップ上に挿入する場合に限り、実際にインクリメントを実行したいのですが、私はマップの演算子[]を調べましたが、私が望むようにそれを働かせてください。どのようにそれを行うには簡単な方法はありますか?それとも私がeverytimmeを挿入する前に、キーを検索しなければならないと私はその後、インクリメントおよび挿入マップ内のオートインクリメントの種類

#include <iostream> 
#include <map> 
#include <string> 

int main() 
{ 
    std::map<std::string,int> mymap; 
    int cnt = 0; 
    int h = -1; 

    mymap.insert(std::pair<std::string, int>("GBP", cnt++)); 
    mymap.insert(std::pair<std::string, int>("EUR", cnt++)); 
    mymap.insert(std::pair<std::string, int>("USD", cnt++)); 
    mymap.insert(std::pair<std::string, int>("GBP", cnt++)); 
    mymap.insert(std::pair<std::string, int>("GBP", cnt++)); 
    mymap.insert(std::pair<std::string, int>("GBP", cnt++)); 
    mymap.insert(std::pair<std::string, int>("CAD", cnt++)); 
    mymap.insert(std::pair<std::string, int>("GBP", cnt++)); 

    std::cout << cnt << std::endl; 

for(const auto & v : mymap) 
    std::cout << v.first << " " << v.second << std::endl; 

    return 0; 
} 

結果はGBP 0、1ユーロ、米ドル2となるものを見つけていない場合は、CAD 4

+1

YourMap [YourKey] ++このコードは、キーが存在する場合は値をインクリメントし、キーが存在しない場合は値= 1のキーを作成します(0の場合はわかりません)。欲しいのですが。 –

+1

ペアの2番目の部分として 'mymap.size()'を使ってみませんか? – immibis

+0

heheはmap.size()を使用しています。これは実際にはとてもスマートです!ありがとうございます – lllook

答えて

2

(6 CADません) insertは、firstが挿入された要素(ここでは面白くない要素)の反復子であり、secondが要素が実際に追加されたかどうかを示すboolであるpairを返します。いつでもマップのサイズが1ずつ増加しますので、

mymap.insert(std::pair<std::string, int>("GBP", mymap.size())); 
mymap.insert(std::pair<std::string, int>("EUR", mymap.size())); 
// and so on. 

だから、あなたはそれをチェックすることもできます。この特定のケースで

if(mymap.insert(std::pair<std::string, int>("GBP", cnt)).second) 
    cnt++; 
if(mymap.insert(std::pair<std::string, int>("EUR", cnt)).second) 
    cnt++; 
// and so on. 

を、しかし、あなたはカウントとしてmymap.size()を使用することができます要素が挿入されます。