Roh*_*wal 1 c++ hash map data-structures
我试图使用Rabin Karp和Binary搜索编写一个最长公共子串程序.为此我写了一个方法,基本上为其中一个字符串创建一个哈希表,键将是从索引i开始的长度为M的模式的哈希值.它们的关键值是索引i.
我写了以下代码:
#include <iostream>
#include <string>
#include<map>
#include<math.h>
#define BASE 10
#define BASE2 10.0
#define M 99999989
using namespace std;
map<int, int> hashmap;
int pHash=0;
int mod(int a, int b) {
return (a%b + b)%b;
}
int getHash(string & pattern) {
int hashVal = 0;
for ( int i =0 ; i<pattern.length();i++) {
int val = (int) pattern[i];
hashVal = mod(hashVal*BASE + val, M);
}
return hashVal;
}
int rabinKarp(string &pattern, string & text)
{
pHash = getHash(pattern);
cout<<"P HASH : "<<pHash<<endl;
int m = pattern.size();
int fHash = getHash(text.substr(0, pattern.size()));
int newKey = fHash;
hashmap.insert(newKey, 0);
if(fHash==pHash)
cout<<"Rabin Karp found a match at index : 0 "<< endl;
for(int i = 1; i <=text.size()-pattern.size();i++) {
int val = (int)text[i-1];
double sz = (double)pattern.size()-1.0;
int temp = pow(BASE2, sz);
int mult= mod(temp,M);
fHash = mod(fHash - mod(val*mult,M),M);
fHash= mod(fHash*BASE, M);
fHash= mod(fHash+(int)text[i+m-1], M);
int key = fHash ;
hashmap.insert(key, i);
if(fHash==pHash)
cout<<"Rabin Karp found a match at index : "<< i<<endl;
}
return 1;
}
int main() {
string pattern;
string text;
cout<<"Please enter the pattern "<<endl;
getline(cin, pattern) ;
cout<<"Please enter the text " <<endl;
getline(cin, text);
int index = rabinKarp(pattern, text) ;
}
Run Code Online (Sandbox Code Playgroud)
问题是我无法将密钥插入地图.我得到以下错误,我没有任何意义.任何人都可以帮我理解这是什么?
错误3错误C2664:'std :: pair <_Ty1,_Ty2> std :: _ Tree <_Traits> :: insert(const std :: pair <_Kty,_Ty>&)':无法将参数1从'int'转换为' const std :: pair <_Ty1,_Ty2>&'c:\ program files\microsoft visual studio 9.0\vc\include\xtree 760 SPOJ
错误2错误C2100:非法间接c:\ program files\microsoft visual studio 9.0\vc\include\xtree 760 SPOJ
如果您尝试插入键值对,则需要分别插入一个std::pair<K, V>,其中K和V分别是键和值类型.请参见std :: map:insert.你需要类似的东西
hashmap.insert(std::make_pair(newKey, 0));
Run Code Online (Sandbox Code Playgroud)
如果要为给定键插入值,并且不介意可能覆盖以前存在的值,则可以使用operator[]:
hashmap[newKey] = someValue;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7786 次 |
| 最近记录: |