查找函数在unordered_map中的工作方式是搜索键值
How find function works in unordered_map is searching for key value
我正在用 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
迭代器不会被取消引用。因此,如果地图为空,这不是问题,因为代码会处理这种情况。
相关文章:
- 以螺旋方式打印矩阵的程序.(工作不好)
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何解决在负数的情况下程序以相同方式工作的问题?
- 在 Eclipse 中添加库的工作方式是否与在 Visual Studio 中相同?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 我的随机生成器是否不工作,或者我决定人/骨架是否击中对手的方式是否有错误
- OpenGL应用程序在不同的计算机上的工作方式不同
- >= <= 没有按照我使用它们的方式工作,我在哪里搞砸了?
- 程序按执行方式工作,直到我向其添加析构函数为止
- 简单的计数和求和函数没有按照我预期的方式工作
- 任何人都有任何想法编写与C 旧手机中的消息作曲家以相同方式工作的程序
- C++ int x++ 和 int ++x 无法按照我想象的方式工作
- 重载输入/输出运算符,为什么它以这种方式工作而不是以另一种方式工作
- 我正试图在我的SFML Platformer中实现双跳,但它并没有按预期的方式工作
- 比率类中的运算符/=以错误的方式工作
- 怪物阵列没有按我需要的方式工作
- C ++设置没有按照我需要的方式工作
- 为什么这段代码以相反的方式工作?
- 为什么情绪分类不能按照 openCV 链接中指定的方式工作?
- 如果两者都以相同的方式工作,那么使用 void func(struct myStruct s) 和 void func(myStruct s) 有什么区别?