Home > Article > Backend Development > How to use counter in c++
counter in C is an STL container used to store and count different values. It uses integer keys and values, inserts or updates values through the [] operator, and provides operations such as traversing, finding the maximum value, and sorting elements. For example, it can be used to count the number of times a word appears.
Understanding counter in C
counter
in C is the standard template library ( STL), is a container class specifically designed to store and count different values. It is similar to an associative container, but focuses more on timing rather than storing data in key-value pairs.
Usage
To use counter
, you need to include the <map>
header file and instantiate a counter
Object:
<code class="cpp">#include <map> std::map<int, int> counter;</code>
counter
Use integers as keys and integers as values to represent the frequency of each key appearing in the container.
Basic operations
[]
operator to insert or update a key value. If the key exists, the value will be updated; otherwise, a new entry will be inserted. []
operator or the at()
method to get the value of the key. If the key does not exist, the at()
method will throw an exception and the []
operator will return 0. erase()
method to delete key-value pairs. Advanced usage
begin()
and end( )
method gets the iterator of the elements in the container, which can traverse key-value pairs. max_element()
method to find the element with the maximum value. sort()
method to sort the elements in a container by value or key. Example
<code class="cpp">// 统计单词出现的次数 std::map<std::string, int> word_counter; // 插入单词及其出现次数 word_counter["hello"]++; word_counter["world"]++; // 查找单词出现的次数 int hello_count = word_counter["hello"]; // 遍历单词及其出现次数 for (auto it = word_counter.begin(); it != word_counter.end(); ++it) { std::cout << it->first << ": " << it->second << std::endl; }</code>
The above is the detailed content of How to use counter in c++. For more information, please follow other related articles on the PHP Chinese website!