查找函数在unordered_map中的工作方式是搜索键值

How find function works in unordered_map is searching for key value

本文关键字:方式 工作 搜索 键值 函数 unordered map 查找      更新时间:2023-10-16

我正在用 leetcode.com 来解决这个问题。问题是2和。链接:2和问题 以下是某人提供的最佳解决方案:

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution{
public:
vector<int> twoSum(vector<int> &nums, int sum){
//write code here
int len = nums.size();
unordered_map<int, int> hashTable;
for(int i=0; i<len; i++){
int diff = sum - nums[i];
auto found = hashTable.find(diff);
if(found == hashTable.end()){
hashTable.insert(pair<int, int>{nums[i], i});
}
else{
return vector<int>{found->second, i};
}
}
}
};
int main()
{
vector<int> myArray;
vector<int> outputArray;
int sum,n,temp;
cout<<"enter the size of the arrayn";
cin>>n;
cout<<"enter the integersn";
for(int i=0; i<n; i++){
cin>>temp;
myArray.push_back(temp);
}
cout<<"enter the sumn";
cin>>sum;
Solution s;
outputArray = s.twoSum(myArray, sum);
cout<<"["<<outputArray[0]<<","<<outputArray[1]<<"]"<<endl;
return 0;
}

在上面的代码中,auto found = hashTable.find(diff);此行的工作方式,因为哈希表从未初始化过。那么,它是如何找到差异值的。然后 if 条件是如何工作的? 当我尝试使用迭代器打印哈希表的内容时,它返回空值,即哈希表为空。那么它是如何找到差异值的呢? 请帮助我理解。 感谢您的所有意见。

当您使用unordered_map::find搜索键时,如果未找到该键,则返回end()迭代器。这是一个非可引用的迭代器,因为它实际上并不指向元素。您可以在下一行中看到,这是正在检查的条件:

if(found == hashTable.end()){

在此分支中,found迭代器不会被取消引用。因此,如果地图为空,这不是问题,因为代码会处理这种情况。

相关文章: