[英]Hash Table implementation in C++ - How to return a key with a particular value
I am trying to solve a programming question using Hash Tables in C++. 我正在尝试使用C ++中的哈希表解决编程问题。 It is supposed to be fairly simple implementation of hash tables. 它应该是哈希表的相当简单的实现。 I am extremely new to Hash Tables and this is my first try at implementation. 我对哈希表非常陌生,这是我第一次尝试实现。
The question is that I have been given an array which contains integers. 问题是给了我一个包含整数的数组。 All but one integer repeats itself twice. 除了一个整数外,所有其他整数都会重复两次。 I have to find an integer that doesn't. 我必须找到一个没有的整数。
Input: {1,2,1,3,3}
Output: 2
My solution is that I will start putting these keys inside a hash table and if I find a key inside the hash table beforehand, I will delete that key from the hash table. 我的解决方案是,我将开始将这些密钥放入哈希表中,如果事先在哈希表中找到了密钥,则将从哈希表中删除该密钥。
My code implementation works but I now I wanted to see how I can get back the right value (2 in this case) since even after erasing the key, the keys remain with value 0. 我的代码实现有效,但是现在我想看看如何获取正确的值(在这种情况下为2),因为即使擦除密钥后,密钥的值仍为0。
Here is my code: 这是我的代码:
int main()
{
int num[5] = {1,2,1,3,3};
map <int,int> mymap;
for(int i=0;i<5;i++)
{
if(mymap.find(num[i])!=mymap.end())
{
mymap.erase(num[i]);
}
else
{
mymap[num[i]] = 10; //10 is just a placeholder value.
}
}
cout<<"0:"<<mymap[0]<<endl;
cout<<"1:"<<mymap[1]<<endl;
cout<<"2:"<<mymap[2]<<endl; //Should only find 10 value in 2
cout<<"3:"<<mymap[3]<<endl;
cout<<"4:"<<mymap[4]<<endl;
}
Output: 输出:
0:0
1:0
2:10
3:0
4:0
std::map
is a tree, not a hash table. std::map
是一棵树,而不是哈希表。 For a hash table you want std::unordered_map
. 对于哈希表,您需要std::unordered_map
。
But to answer your question: 但是要回答你的问题:
You can use the map iterator to get the only remaining value: 您可以使用地图迭代器获取唯一的剩余值:
if (!mymap.empty()) {
cout << mymap.begin()->first;
}
But beware - when you call cout << mymap[X]
, it also adds X
to the map. 但是要当心-调用cout << mymap[X]
,它还会将 X
添加到地图中。 So remove all those debugging lines at the end. 因此,最后删除所有这些调试行。
And by the way - when you don't have a value, just a key, then you can use a set
instead (or unordered_set
). 顺便说一句-当您没有值时,只有一个键,则可以使用set
(或unordered_set
)。
Just increment the value in the map, as the integers are default constructed (and thus initialized to 0
): 只需增加映射中的值即可,因为整数是默认构造的(并因此初始化为0
):
int num[5] = {1,2,1,3,3};
unordered_map <int,int> mymap;
for(int i=0;i<5;i++)
{
++mymap[num[i]];
}
cout<<"0:"<<mymap[0]<<endl;
cout<<"1:"<<mymap[1]<<endl;
cout<<"2:"<<mymap[2]<<endl; //Should only find 10 value in 2
cout<<"3:"<<mymap[3]<<endl;
cout<<"4:"<<mymap[4]<<endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.