c++查找映射值和键

c++ Find map value and key

本文关键字:映射 查找 c++      更新时间:2023-10-16

我正试图找到一种方法,在映射中搜索键,在消息中返回,获取找到的键的值,然后在另一条消息中返回。例如,下面的类有一个在杂货店找到的水果列表,我想创建一个if-then-else语句来在地图中找到水果名称,在下面的消息中返回其名称,然后在另一个输出中返回其价格。我该怎么做?

`

#include <iostream>
#include <string>
#include <set>
#include <map>
#include<utility>
using namespace std;

int main()
{
map<string,double> items;
items["apples"] = 1.56;
items["oranges"] = 2.34;
items["bananas"] = 3.00; 
items["limes"] = 4.45;       
items["grapefruits"] = 6.00;    
string fruit = "apples";
//If a fruit is in map
cout << "Your fruit is: " << "(fruitname value here)"
    <<"n";
    << "your price is: " <<"(fruitname price here)" 
    << "n";
 // return the fruitname and its price


  return 0;
}

到目前为止,我只看到了展示如何打印整个地图的例子。我看到的最接近的是这个链接上发布的一个(见第二篇文章):看看映射c++中是否有键,但我对语法感到困惑,特别是"buf.c_str()".

由于映射的键是std::string,因此不必使用.c_str()。您可以传递std::string对象本身:

auto it = items.find(fruit); //don't pass fruit.c_str()
if ( it != items.end())
   std::cout << "value = " << it->second << std::endl;
else
   std::cout << ("key '" + fruit + "' not found in the map") << std::endl;

非常简单:

auto it = items.find(fruit);
if (it != items.end())
{
    std::cout << "Your fruit is " << it->first << " at price " << it->second ".n";
}
else
{ 
    std::cout << "No fruit '" << fruit << "' exists.n";
}

使用mapfind成员函数。

map<string,double>::const_iterator i = items.find(fruit);
if(i != items.end())
    cout << "Your fruit is: " << i->first << "n" << "your price is: " << i->second << "n";