如何使用find方法更新std :: map?

如何使用find方法更新std::map中的键的值?

我有一个像这样的映射和迭代器声明:

 map <char, int> m1; map <char, int>::iterator m1_it; typedef pair <char, int> count_pair; 

我正在使用地图来存储一个字符的出现次数。

我正在使用Visual C ++ 2010。

std::map::find返回一个迭代器到find的元素(或者如果没有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 <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' 

所以使用这种技术,读取stream中的所有字符并计算它们变得非常简单:

 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 } 

你可以std::map::at成员函数中使用std::map::at ,它会返回一个对用key k标识的元素的映射值的引用。

 std::map<char,int> mymap = { { 'a', 0 }, { 'b', 0 }, }; mymap.at('a') = 10; mymap.at('b') = 20; 

你也可以这样做 –

  std::map<char, int>::iterator it = m.find('c'); if (it != m.end()) (*it).second = 42;