The number of elements can be counted by using map. The following three methods are mainly introduced:
1. Use find function to count the times of each element
void test_map2() { string strs[] = { "Apple", "Banana", "Strawberry", "Apple", "Banana", "Banana", "Banana", "Apple", "Banana", "Strawberry" }; map<string, int> countmap; //Using find to count the number of occurrences of each element for (const auto& e : strs) { map<string, int>::iterator it = countmap.find(e); //countmap.end() is the next element of the last element in the map if (it != countmap.end()) { //If found, value + +; it->second++; } else { //If you don't insert it again, you have to traverse it again. It's a little redundant countmap.insert(make_pair(e, 1)); } } //Traverse each element map<string, int>::iterator cit = countmap.begin(); while (cit != countmap.end()) { cout << cit->first << ":" << cit->second << endl; cit++; } }
2. Use insert to count the times of each element
void test_map3() { string strs[] = { "Apple", "Banana", "Strawberry", "Apple", "Banana", "Banana", "Banana", "Apple", "Banana", "Strawberry" }; map<string, int> countmap; //pair<iterator,bool> insert (const value_type& val); //The return value of this type of insert is a pair, the first element is an iterator, pointing to the map of the newly inserted element, and the second element is a bool value. If the insert succeeds, true will be returned, otherwise false will be returned for (const auto& e : strs) { std::pair<std::map<std::string, int>::iterator, bool> ret = countmap.insert(make_pair(e, 1)); if (ret.second == false) { ret.first->second++; } } map<string, int>::iterator cit = countmap.begin(); while (cit != countmap.end()) { cout << cit->first << ":" << cit->second << endl; cit++; } }
3. Use operator [] to count the number of occurrences of each element
void test_map4() { string strs[] = { "Apple", "Banana", "Strawberry", "Apple", "Banana", "Banana", "Banana", "Apple", "Banana", "Strawberry" }; map<string, int> countmap; for (const auto& e : strs) { //Call operator []; then + + the return value. countmap[e]++; } for (auto& e : countmap) { cout << e.first << ":" << e.second << endl; } }
Output results of the above three methods:
If you don't understand how to count the times with operator [], please refer to the blog https://blog.csdn.net/yam_sunshine/article/details/89930311
It details the usage and principle of operator [].