我正在尝试找出一种方法来在 map 中搜索键,在消息中返回它,获取找到的键的值,并在另一条消息中返回它。例如,下面的类有一个在杂货店找到的水果列表,我想创建一个 if than else 语句来在 map 中找到 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;
}
到目前为止,我只看到了展示如何打印整个 map 的示例。我见过的最接近的是发布在这个链接上的那个(见第二篇文章):see if there is a key in a map 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;
关于c++查找 map 值和键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032529/