【问题标题】:C++ Unordered MapC++ 无序映射
【发布时间】:2015-06-17 19:26:25
【问题描述】:

我有一个程序,我在其中使用迭代器来访问映射条目的值。

#include <iostream>
#include <cstdio>
#include <unordered_map>
#include <utility>
#include <algorithm>

using namespace std;

int main()
{
   int a[]={1,2,4,7,9,3,3,55,66,88,11};
   int k = 58;
   unordered_map<int,int> c;
   int i=0;
   for(auto x: a)
   {
       c.insert(make_pair(x,i));
       i++;
   }

   for(auto x: c)
   {
     if(c.count(k-x.first)==1) printf("%d %d\n",x.second,(c.find(k-x))->second);
   }

}

行内:

if(c.count(k-x.first)==1) printf("%d %d\n",x.second,(c.find(k-x))->second);

我遇到了错误,尤其是在 c.find()-&gt;second 中。我认为这是从迭代器访问元素的方式。怎么了?

【问题讨论】:

    标签: c++ dictionary stl unordered-map


    【解决方案1】:

    你不能说

    c.find(k-x)
    

    因为kintxstd::pair&lt;int, int&gt;。您是指这两者之一吗?

    c.find(k - x.first)
    

    或者

    c.find(k - x.second)
    

    作为旁注,直接从find 取消引用返回的迭代器通常是不安全的,因为如果find 返回.end()(例如,它没有找到具有该键的元素),那么您已经有问题。

    【讨论】:

    • 是的,我在 count 中做到了,在 find 中忘记了。非常感谢。
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多