地图STL的第二个元素的默认值?

Default value for the second element of the map STL?

如果我用数组初始化地图 STL 中第二个元素的默认值是多少? 例如:

 #include <bits/stdc++.h> 
using namespace std; 
  
void countFreq(int arr[], int n) 
{ 
    unordered_map<int, int> mp; 
  
    // Traverse through array elements and 
    // count frequencies 
    for (int i = 0; i < n; i++) 
        mp[arr[i]]++; 
  
    // Traverse through map and print frequencies 
    for (auto x : mp) 
        cout << x.first << " " << x.second << endl; 
} 
  
int main() 
{ 
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    countFreq(arr, n); 
    return 0; 
} 

这个程序如何通过访问map mp的第二个元素来return获取数组中元素的频率?

默认情况下,映射的第二个元素在尝试访问其键至少 once.So 后初始化为 0(如果其类型在代码中为 int),当您第一次访问某些元素x, mp[x] 变为0 然后在你的代码中计数时加1.

what is the default value for the second element in map STL if I am initializing it with an array?

当使用 operator[] 访问 std::map 中的键值对 (kvp) 时,键已经存在,或者构造了一个新的 kvp 并且 mapped_typevalue-initialised. A value-initialized int is always 0. This imposes a requirement that it must be default constructible. Note that you can also access entries in a map using the at 成员函数,如果找不到键则抛出。

How can this program return the frequency of the element in the array by accessing the second element of map mp?

您已在代码段中正确完成此操作。您可以使用 std::multiset or std::unordered_multiset, they provide a count 成员函数,即键的频率。

#include <set>
#include <iostream>

int main() 
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; 
    std::multiset<int> freq (std::begin(arr), std::end(arr));

    for(auto elem = freq.begin();
        elem != freq.end();
        elem=freq.upper_bound(*elem)) // Traverse the unique elements
    {
        std::cout << *elem << " count: " << freq.count(*elem) << "\n";
    }
}

Godbolt


请注意,您的问题提到了 std::map,但您提供的示例引用了 std::unordered_map,其中大部分适用于两种数据结构。