📜  如何在C++映射中查找具有最大价值的条目

📅  最后修改于: 2021-05-30 13:11:54             🧑  作者: Mango

给定C++中的映射,任务是在此映射中找到具有最高值的条目。

例子:

Input: Map = {ABC = 10, DEF = 30, XYZ = 20}
Output: DEF = 30

Input: Map = {1 = 40, 2 = 30, 3 = 60}
Output: 3 = 60

方法

  1. 在迭代器的帮助下逐项迭代地图项
    map::iterator itr;
    for (itr = some_map.begin();
         itr != some_map.end();
         ++itr) 
    {
        // operations
    }
    
  2. 将第一个条目存储在参考变量中以进行初始比较。
  3. 如果当前条目的值大于参考条目的值,则将当前条目存储为参考条目。
  4. 对地图中的所有条目重复此过程。
  5. 最后,参考变量具有必需的条目,该条目在地图中具有最高的值。
  6. 打印此条目

下面是上述方法的实现:

// C++ program to find the Entry
// with largest Value in a Map
  
#include 
using namespace std;
  
// Function to print the Map
void printMap(map sampleMap)
{
    map::iterator itr;
    for (itr = sampleMap.begin();
         itr != sampleMap.end();
         ++itr) {
        cout << itr->first
             << " = " << itr->second << ", ";
    }
    cout << endl;
}
  
// Function tp find the Entry
// with largest Value in a Map
pair findEntryWithLargestValue(
    map sampleMap)
{
  
    // Reference variable to help find
    // the entry with the highest value
    pair entryWithMaxValue
        = make_pair(0, 0);
  
    // Iterate in the map to find the required entry
    map::iterator currentEntry;
    for (currentEntry = sampleMap.begin();
         currentEntry != sampleMap.end();
         ++currentEntry) {
  
        // If this entry's value is more
        // than the max value
        // Set this entry as the max
        if (currentEntry->second
            > entryWithMaxValue.second) {
  
            entryWithMaxValue
                = make_pair(
                    currentEntry->first,
                    currentEntry->second);
        }
    }
  
    return entryWithMaxValue;
}
  
// Driver code
int main()
{
  
    // Map
    map sampleMap;
    sampleMap.insert(pair(1, 40));
    sampleMap.insert(pair(2, 30));
    sampleMap.insert(pair(3, 60));
  
    // Printing map
    cout << "Map: ";
    printMap(sampleMap);
  
    // Get the entry with largest value
    pair entryWithMaxValue
        = findEntryWithLargestValue(sampleMap);
  
    // Print the entry
    cout << "Entry with highest value: "
         << entryWithMaxValue.first << " = "
         << entryWithMaxValue.second << endl;
  
    return 0;
}
输出:
Map: 1 = 40, 2 = 30, 3 = 60, 
Entry with highest value: 3 = 60
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”