【问题标题】:c++ Find map value and keyc ++查找映射值和键
【发布时间】: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()”。

【问题讨论】:

    标签: c++ map key


    【解决方案1】:

    由于映射的键是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;
    

    【讨论】:

    • 这种技术优于operator[]。如果元素不存在,operator[] 具有插入元素的副作用。
    • @ThomasMatthews:它不仅优于operator[],而且是正确的。使用operator[] find 元素是错误的!
    • 仅供参考,我说的是value = items["orange"];的案例。
    • @ThomasMatthews:那是不正确的。所以这与 preference 本身无关。
    • @Nawaz 因为每个海报都给出了相似的答案,我不太确定该给谁打绿色复选标记。它们中的每一个在测试时都有效,但为什么像 amaurea 使用的示例那样,“自动”优于迭代器?
    【解决方案2】:

    很简单:

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

    【讨论】:

      【解决方案3】:

      使用maps 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";
      

      【讨论】:

      • 当我尝试测试这个函数时,我得到了这个错误:"no match for operator!=" 它指的是 "if(fruit !=items.end()){"。
      • @Wormhole88:抱歉,应该是i != items.end()。我已经更新了答案。
      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 2014-08-19
      • 1970-01-01
      • 2019-07-23
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多