Home  >  Article  >  Backend Development  >  How to use counter in c++

How to use counter in c++

下次还敢
下次还敢Original
2024-04-26 17:54:161179browse

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.

How to use counter in c++

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

  • Insert or update a value: Use the [] operator to insert or update a key value. If the key exists, the value will be updated; otherwise, a new entry will be inserted.
  • Get the value: Use the [] 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.
  • Delete values: Use the erase() method to delete key-value pairs.

Advanced usage

  • Traversal: Use begin() and end( ) method gets the iterator of the elements in the container, which can traverse key-value pairs.
  • Find the maximum element: Use the max_element() method to find the element with the maximum value.
  • Sort: Use the 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn