【问题标题】:C++ Loop through first K elements of unordered_mapC++ 循环遍历 unordered_map 的前 K 个元素
【发布时间】:2022-01-03 10:14:10
【问题描述】:

我有一个存储整数计数的 unordered_map。我想遍历地图,但不是获取所有条目,我只想获取第一个 K。保证地图有超过 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 个条目?

【问题讨论】:

  • 您可以使用std::advancestd::next。地图不提供随机访问迭代器,这就是为什么你拥有它会导致错误。更多信息:stackoverflow.com/a/21626211/920069

标签: c++ stl unordered-map


【解决方案1】:

如果您可以使用 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";

【讨论】:

  • 不幸的是我不能在项目中使用 C++20。但是非常感谢这个解决方案。不知道这一点。
【解决方案2】:

我只希望获得第一个 K

std::unordered_map documentation的备注

unordered_map 对象不保证将哪个特定元素视为其第一个元素。

这实质上意味着无法保证您将按插入顺序迭代元素。

要遍历地图的元素,您可以使用:

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;
}

【讨论】:

  • 是的,你是对的。我关心的是从地图中取出任何 K 个元素,不一定是第一个 K 推入 unordered_map 的元素
  • @VamsiKrishna 我在答案末尾添加了一个工作示例。看看这个。您只需使用一个count 变量,当它达到变量K 的值时,该变量将用于循环外的K,在我的示例中为3
  • 感谢 Anoop Rana。我想我将不得不使用像这样的某种解决方法,而不是 u-map.begin()+k
  • @VamsiKrishna 不客气。如果对您有帮助,您能否将我的答案(或任何其他)标记为正确。
  • 完成 :) Anoop Rana
猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 2016-05-29
  • 1970-01-01
  • 2013-01-19
  • 2020-06-11
  • 2012-01-04
  • 1970-01-01
  • 2016-01-26
相关资源
最近更新 更多