c ++查找地图值和键

时间:2013-02-22 20:19:01

标签: c++ map key

我正试图找出一种方法来搜索地图中的密钥,在邮件中返回密钥,获取找到的密钥的值,然后将其返回到另一条消息中。例如,下面的类有一个在杂货店找到的水果列表,我想创建一个if than else语句来查找地图中的fruitname,在下面的消息中返回其名称,然后在另一个输出中返回其价格。我怎么能这样做?

`

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

到目前为止,我只看到了展示如何打印整个地图的示例。我见过的最接近的是在这个链接上发布的那个(见第二篇文章):see if there is a key in a map c++,但我对语法感到困惑,特别是“buf.c_str()”。

3 个答案:

答案 0 :(得分:2)

由于地图的密钥为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;

答案 1 :(得分:1)

非常简单:

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

答案 2 :(得分:1)

使用map s find成员函数。

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