Home > Enterprise >  How to print a whole pair by just a key value in map c ?
How to print a whole pair by just a key value in map c ?

Time:10-23

Let's say I'm having a map of integer key value!

map<int,string>a={{1,"one"},{2,"two"}}; 

How can I print a whole pair by just supplying a key value?

Let's say user entered 1; I want my code to print 1,one then,How can i do so?

CodePudding user response:

I've a map and user has to supply a key value,If that key value is present in that map,Then I've add that whole "pair" in different map, Is it possible to do so?

Yes this is possible. You can use std::map::find to check if your input map contains a given key and then std::map::insert to add the key value pair into the output map as shown below:

int main()
{
    std::map<int,string> searchMap={{1,"one"},{2,"two"}}; //map in which key is to be searched 
    
    std::map<int, string> outputMap;
    
    int input =0; 
    if(std::cin >> input); //take input from user 
    {
        //search the map for the input key 
        auto findInput = searchMap.find(input);
        if(findInput!=searchMap.end())//check if the input was found inside the map 
        {
            std::cout << "The map contains the key: " << input << " entered by user" << std::endl;
            //add the key value pair to the outputmap 
            outputMap.insert({input,findInput->second});  //or just outputmap[input] = findInput->second
        }
        else 
        {
            std::cout <<"The map does not contain the key: " << input << " entered by user" << std::endl;
        }
    }
    
    //lets confirm that outputmap was filled with input 
    for(const auto&[key, value]:outputMap)
    {
        std::cout << key << "->" << value << std::endl;
    }
    
}

Working demo

  •  Tags:  
  • c
  • Related