So here's a simple program that just search for two numbers in an array that sum up to a certain value k
#include <iostream>
#include <bits/stdc .h>
using namespace std;
int main()
{
unordered_set<int> hashtable;
int k =7;
int arr[5] = {1, 2, 3, 4, 5};
int s = sizeof(arr);
for (int i =0; i<s; i ){
if( hashtable.find(k - arr[i])!= hashtable.end() )
{
cout << arr[i] << endl;
cout<< "found one " << arr[i] << " and "<< k-arr[i]<< endl;
} else {
hashtable.insert(arr[i]);
}
}
return 0;
}
And here's the out put, I am getting
4
found one 4 and 3
5
found one 5 and 2
7
found one 7 and 0
7
found one 7 and 0
Am I missing something?
CodePudding user response:
You access the array outside of its bounds. The behaviour of the program is undefined.
sizeof
does not yield the number of elements in an array. It yields the size of an object in bytes. When the size of the element is more than one byte - and int
is more than one byte on most systems - then the number of bytes in the array is more than the number of elements.
A correct way to get the number of elements in an array is to use std::size
:
int s = std::size(arr);
CodePudding user response:
Since you use only arr[i]
and not i
itself, you can write for (auto a : arr)
. This will respect the array bounds, you don't need to calculate the maximum index. Hence, it avoids the wrong calculation (which the other answers fix)
CodePudding user response:
Maybe there are other ways to get the size of an array but for now this will do :
int s = sizeof(arr)/sizeof(arr[0]);