c++查找 map 值和键

标签 c++ dictionary key

我正在尝试找出一种方法来在 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/

相关文章:

用变量形成的 symfony 翻译键

c++ - 是否可以在linux下启动或停止屏保时得到通知

dictionary - Xquery 中的字典

arrays - (整数)作为结构数组的 slice 索引

python - 从范围在python中创建字典对象

java - 对ECC公钥的长度感到困惑

php - 用数字键替换关联数组键的最快方法

c++ - 是否可以在 C++14 中分配和验证 constexpr 结构?

c++ - 快速将 uint32_t 转换为二进制

c++ - 了解如何在链接列表的末尾添加新节点