【问题标题】:Default value for the second element of the map STL?地图 STL 的第二个元素的默认值?
【发布时间】:2021-05-17 06:19:38
【问题描述】:

如果我用数组初始化 map 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的第二个元素返回数组中元素的频率?

【问题讨论】:

  • 不在地图中的项目的默认值为0。
  • @drescherjm 假设您使用 operator[]
  • 是的,新的映射值为value initialized。对于int,这意味着zero initialized
  • mp[arr[i]]++ 执行时,它要么增加一个现有值,要么在必要时创建一个新的键值对并将增量前的值初始化为零。
  • this documentation 中描述了所发生的事情。如果您是 C++ 文档的新手,可能不清楚,但那里有详细信息。

标签: c++ dictionary data-structures stl


【解决方案1】:

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

当使用operator[] 访问std::map 中的键值对(kvp) 时,该键已经存在,或者构造了一个新的kvp 并且mapped_typevalue-initialised。值初始化的 int 始终为 0。这要求它必须是默认可构造的。请注意,您还可以使用 at 成员函数访问映射中的条目,如果找不到键,则会抛出异常。

这个程序如何通过访问map mp的第二个元素返回数组中元素的频率?

您已在代码 sn-p 中正确执行此操作。您可以使用std::multisetstd::unordered_multiset,它们提供了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,这在很大程度上适用于两种数据结构。

【讨论】:

    【解决方案2】:

    map 的第二个元素在尝试访问其键至少一次后默认初始化为 0(如果它的类型是 int,如代码中所示)。因此,当您第一次访问某个元素 x 时,mp [x] 变为 0,然后在您的代码中计数时增加 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多