メソッドstd::mapを使用した後にキーの値を更新するにはどうすればよいfindですか?
私はこのようなマップとイテレータ宣言を持っています:
map <char, int> m1;
map <char, int>::iterator m1_it;
typedef pair <char, int> count_pair;
マップを使用して、文字の出現回数を保存しています。
Visual C ++ 2010を使用しています。
回答:
std::map::find見つかった要素(またはend()要素が見つからなかった場合)へのイテレータを返します。mapがconstでない限り、イテレータが指す要素を変更できます。
std::map<char, int> m;
m.insert(std::make_pair('c', 0));  // c is for cookie
std::map<char, int>::iterator it = m.find('c'); 
if (it != m.end())
    it->second = 42;
mapドキュメントを参照してくださいmap。
                    error: assignment of member 'std::pair<char* const, char*>::second' in read-only object:(
                    演算子[]を使用します。
map <char, int> m1;
m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.
// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'
したがって、この手法を使用すると、ストリームからすべての文字を読み取り、それらを数えることが非常に簡単になります。
map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;
for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}
[]後に使用することを提案していると信じているかもしれfindません(これがあなたの意図ではなかったと思います)。
                    end()イテレータの逆参照は未定義の動作であり、生成する必要はありませんSIGSEGV(私の経験では、生成する可能性は低いです)。
                    キーがすでにわかっている場合は、を使用してそのキーの値を直接更新できます。 m[key] = new_value
これが役立つかもしれないサンプルコードです:
map<int, int> m;
for(int i=0; i<5; i++)
    m[i] = i;
for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
//Output: 0 1 2 3 4
m[4] = 7;  //updating value at key 4 here
cout<<"\n"; //Change line
for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
// Output: 0 1 2 3 7    
次のように値を更新できます
   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }