【发布时间】:2013-02-22 20:19:00
【问题描述】:
我正在尝试找出一种方法来搜索地图中的键,在消息中返回它,获取找到的键的值,然后在另一条消息中返回它。例如,下面的类有一个在杂货店找到的水果列表,我想创建一个 if than 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;
}
到目前为止,我只看到了展示如何打印整个地图的示例。我见过的最接近的是在此链接上发布的(见第二篇文章):see if there is a key in a map c++,但我对语法感到困惑,特别是“buf.c_str()”。
【问题讨论】: