c++查找映射值和键
c++ Find map value and key
我正试图找到一种方法,在映射中搜索键,在消息中返回,获取找到的键的值,然后在另一条消息中返回。例如,下面的类有一个在杂货店找到的水果列表,我想创建一个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";
}
使用map
的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";
相关文章:
- 如何在多映射的字符串中查找子字符串
- 由并发无序映射查找线程调用的函数是否安全?
- if else VS映射查找
- std::使用迭代器映射查找距离,程序不会终止
- 将长位数组映射到查找表
- C++ 映射查找值和关联的键
- c 映射::查找或映射:: iterator,它是更有效的W.R.T复杂性
- 性能映射 C++ 查找(G++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3))
- 如何遍历 STL 映射(查找所有可能的对)
- 使用映射 c++ 查找矢量的多种模式
- 映射查找函数调用 Vs 将查找缓存为静态变量
- C++多映射查找失败
- 如何优化无序映射查找
- C++ 映射查找找不到特定键
- STL哈希表[无序映射]查找性能与大小
- 使用映射查找具有给定和(带有负数)的子数组
- TBB 并发哈希映射查找和插入
- 定时矢量与映射与未定义映射查找
- c++使用无序键组合进行映射查找
- STL映射查找第一个不可重复的字符