【问题标题】:How to see if a key is present in a map?如何查看地图中是否存在密钥?
【发布时间】:2011-09-07 20:24:15
【问题描述】:

我有两个像 map<int,int> 这样的 stl 映射,我想比较它们..所以这里是代码..

map <int, int> a,b;
insert into a and b;
map<int,int>::iterator i;

for(i=a.begin();i!=a.end();i++){
    if(what should be here?)
         then cout << (*i).first << " also present in b" << endl;
}

我希望类似 (b[(*i).first]).exist??

【问题讨论】:

标签: c++ stl map


【解决方案1】:

map::find 用作:

for(i=a.begin(); i!=a.end(); i++)
{
  if( b.find(i->first) != b.end() )
       std::cout << (*i).first << " also present in b" << std::endl;
}

注意i-&gt;first(*i).first 是一样的。

【讨论】:

    【解决方案2】:

    使用map::find()

    【讨论】:

      【解决方案3】:

      如果 i->first(i 指向的元素的键)存在于 b 中,则返回 true。

      if (b.find(i->first) != b.end())
      

      【讨论】:

        【解决方案4】:

        您不能使用operator[],因为如果它不存在,它将创建密钥。相反,请使用find:

        map<int,int>::const_iterator it = b.find(a->first);
        if( it == b.end() )
          // NOT FOUND
        

        【讨论】:

          【解决方案5】:

          std::map 有一个名为 find 的函数,用于在地图中查找键。见this

          所以代码应该是:

          if( b.find( i->first ) != b.end() )
          

          【讨论】:

            【解决方案6】:

            我喜欢b.count(i-&gt;first) &gt; 0

            【讨论】:

            • -1:我不这样做,因为那会贯穿整个地图。如果它是多图或多集,这是浪费。你只需要知道至少有一个;无需全部计算。
            • 什么? A)它不是多图,所以 B)不,它不会遍历整个地图。当然,如果它是多地图,我会使用 find,但这更简洁,适用于地图。
            • 参见例如stackoverflow.com/questions/3886593/…(顺便说一句,这个问题可能是重复的)。
            • @John:即使在多地图中,它也不会遍历整个地图;在最坏的情况下,它会遍历键的范围。
            【解决方案7】:

            map::find函数

            我会这样做:

            std::map <int, int> a,b;
            insert into a and b;
            std::map<int,int>::iterator it = a.begin();
            std::map<int,int>::iterator ite = a.end();
            
            while (it != ite)
            {
              if (b.find(it->first) != b.end())
              {
                std::cout << it->first << " also present in b" << std::endl;
              }
              ++it;
            }
            

            【讨论】:

              【解决方案8】:

              出于性能原因,我建议您执行以下操作:

              map<int,int>::iterator ia  = a.begin(), ib  = b.begin(),
                                     iae = a.end()  , ibe = b.end();
              while(ia != iae && ib != ibe) {
                if      (ia->first < ib->first) ia++;
                else if (ia->first > ib->first) ib++;
                else {
                  cout << ia->first << " also present in b" << endl;
                  ia++; ib++;
                }
              
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-08-27
                • 1970-01-01
                • 2013-07-03
                • 2020-08-19
                • 1970-01-01
                相关资源
                最近更新 更多