C++ 遍历 unordered_map 的前 K 个元素

C++ Loop through first K elements of unordered_map

我有一个 unordered_map 存储整数的计数。我想遍历地图,但不是获取所有条目,我只想获取第一个 K.It 保证地图有超过 K 个条目。

当我执行以下操作时,我 运行 遇到了问题:

  unordered_map<int, int> u_map;
  // Logic to populate the map
  
  for(auto it=u_map.begin(); it!=u_map.begin()+2; it++)
  cout<<it->first<<" "<<it->second<<endl;

表达式 u_map.begin()+2 导致了问题。

那么是否可以在 C++ 中使用 for_each 循环仅获取映射的前 K 个条目?

I only wish to get the first K

来自 std::unordered_map documentation

的注释

an unordered_map object makes no guarantees on which specific element is considered its first element.

这实际上意味着不能保证您将按插入顺序迭代元素。

要迭代地图的元素,您可以使用:

int count  = 0;
for (auto& it: u_map) {
    /* some code here like you can keep a count variable that will check if it 
    reaches the number K and then break the loop. But remember that it is 
    **not** guaranteed that the elements you will get will be in inserted order.*/
   
   if(count < K)
   {
    cout<<it.first<<" "<<it.second<<endl;
   }
   else 
   {
      break;
   }
   ++count;
}

工作示例

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
std::unordered_map<std::string, std::string> u_map = {
        {"RED","#FF0000"},
        {"GREEN","#00FF00"},
        {"BLUE","#0000FF"},{"PURPLE","#0F00FF"},{"WHITE","#0000RF"},{"ORANGE","#F000FF"}
    };
   int K = 3; 
   int count  = 0;
   for (auto& it: u_map) 
   {
       if(count < K)
       {
            cout<<it.first<<" "<<it.second<<endl;
       }
       else 
       {
            break;
        }
        ++count;
    }
return 0;
}

如果你可以使用 C++20,那么 views::take 是一个选择。

#include <unordered_map>
#include <ranges>
#include <iostream>

int main() {
  std::unordered_map<int, int> u_map;
  for (auto [key, value] : u_map | std::views::take(2))
    std::cout << key << " " << value << "\n";
}

C++20 之前的替代方案,使用 std::next:

std::unordered_map<int, int> u_map;
auto end = std::next(u_map.begin(), 2);
for (auto it = u_map.begin(); it != end; ++it)
  std::cout << it->first << " " << it->second << "\n";