J
John Harrison
Thanks for everyone's help so it looks like map is the standard and
should be available for any platform? But hash_map is not standard.
Right.
The reason I am asking for hash table is because I need to write a
function that finds the overlap of two integer array. I am currently
doing:
#include<stdlib.h>
#include<string.h>
#include<sys/int_limits.h>
#define SIZE ((sizeof(int)) * (INT16_MAX) * (2))
void find(int* one,int c1,int* two,int c2){
int i;
int* buffer = malloc(SIZE);
memset((void*)buffer,0,SIZE);
for(i = 0; i < c1; i++)
buffer[one + INT16_MAX] = 1;
for(i = 0; i < c2; i++)
if(buffer[two + INT16_MAX])
printf("%d\n",two);
free(buffer);
}
int main(int argc,char** argv){
int a[] = {1,3,45,6,4,-1,8};
int b[] = {4,2,4,222,8,45,-1};
find(a,7,b,7);
}
this gives me a O(n) algr. but seems to be wasting a lot of memory so
I am thinking using a hashtable instead. am i in the right track?
Thanks!
I think the standard answer would be to use a set. This is untested code.
#include <set>
#include <algorithm>
#include <iterator>
#include <iostream>
void find(int* one,int c1,int* two,int c2)
{
std::set<int> common;
common.insert(one, one + c1);
common.insert(two, two + c2);
// output common elements to cout
std::copy(common.begin(), common.end(),
std:stream_iterator<int>(std::cout, "\n"));
}
That is an O(N lg N) algorithm.
john