[英]C++ Unordered Map
I have a program in which I am using an iterator to get access to a value of a map entry . 我有一个程序在其中使用迭代器来访问映射条目的值。
#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);
}
}
In the line: 在该行中:
if(c.count(k-x.first)==1) printf("%d %d\n",x.second,(c.find(k-x))->second);
I am getting errors especially in c.find()->second
. 我遇到错误,尤其是在c.find()->second
。 I think it is the way to access elements from the iterator. 我认为这是从迭代器访问元素的方式。 What is wrong? 怎么了?
You cannot say 你不能说
c.find(k-x)
Because k
is an int
and x
is a std::pair<int, int>
. 因为k
是一个int
, x
是一个std::pair<int, int>
。 Do you mean one of these two? 您是这两个意思之一吗?
c.find(k - x.first)
Or 要么
c.find(k - x.second)
As a side note, it is generally unsafe to directly derefernce the returned iterator from find
because if find
returns .end()
(as in, it didn't find an element with that key) then you've got a problem. 附带说明一下,直接从find
取消对返回的迭代器的引用通常是不安全的,因为如果find
返回.end()
(例如,它没有找到具有该键的元素),那么您就会遇到问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.