簡體   English   中英

使用基於范圍的 for 循環迭代 map 的值

[英]Iterate values of a map using range-based for loop

最近我開始使用基於范圍的 for 循環。 我遇到了一個問題,我需要按值對 map 進行排序,然后檢查值是否比其他元素/數字更小/更大。 我可以用這個循環做到這一點嗎?

for (auto& it : M){
    // assign only a value to vector
}

如果我有一個成對的向量,這個問題將是相同的,我可以只檢查第二個,如果它比其他元素或數字大嗎? 所有這些都使用基於范圍的 for 循環。

從 C++20 開始,您可以使用views::values獲取std::mapvector<pair>的值:

for (auto v : m | std::views::values)  // m is some map
  // ...

演示

您可以類似地使用views::keys獲取鍵。

使用 C++20 視圖僅顯示 map 中值大於 2 的條目的示例。

#include <iostream>
#include <map>
#include <string>
#include <ranges>

std::map<std::string, int> my_map
{
    {"one", 1},
    {"two", 2},
    {"three", 3},
    {"four", 4}
};

int main()
{

    // create a lambda predicate (a predicate is a function that returns a bool)
    // https://en.cppreference.com/w/cpp/language/lambda
    auto greater_then_2 = [](const auto& pair)
    {
        // use structured binding for readability 
        // (I don't like std::pairs at all for maintainability)
        // https://en.cppreference.com/w/cpp/language/structured_binding
    
        auto [key, value] = pair; // key = pair.first, value = pair.second

        // evaluate predicate
        return value > 2;
    };

    // now loop over all pairs in the map and filter them (C++20 feature)
    // combine structured binding with range based for loops and filters
    for (const auto& [key, value] : my_map | std::views::filter(greater_then_2))
    {
        std::cout << "key = " << key << ", value = " << value << "\n";
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM