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()
。が const でない限りmap
、反復子が指す要素を変更できます。
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 <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
}