【发布时间】:2010-04-01 23:08:53
【问题描述】:
我已经定义了一个结构 ABC 来包含一个 int ID、字符串 NAME、字符串 LAST_NAME;
我的程序是这样的:从输入文件中读取一行。将每一行解析为名字和姓氏并插入到 ABC 结构中。此外,结构的 ID 由输入行的编号给出。
然后,将结构 push_back 放入向量主列表中。我还将这些散列到定义为 vector
如果我的数据是:
加菲猫
史努比狗
猫人
然后,对于关键字 cash 散列到包含 Garfield Cat 和 Cat Man 的向量。我再次使用 push_back 将结构插入到哈希表中。
问题是,当我在我的 masterlist 上调用 stable_sort 时,我的哈希表由于某种原因受到影响。 我认为这可能会发生,因为歌曲的排序方式不同,所以我尝试复制主列表并对其进行排序,尽管原始主列表不受影响,但它仍然会影响哈希表。
任何想法为什么会发生这种情况?
编辑——发布源代码:
这里是主要的
ifstream infile;
infile.open(argv[1]);
string line;
vector<file> masterlist;
vector< vector<node> > keywords(512);
hashtable uniquekeywords(keywords,512);
int id=0;
while (getline(infile,line)){
file entry;
if (!line.empty() && line.find_first_not_of(" \t\r\n")!=line.npos){
id++;
string first=beforebar(line,0);
string last=afterbar(line);
entry.first=first;
entry.last=last;
entry.id=id;
masterlist.push_back(entry);
int pos=line.find_first_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
while (pos!=(int)line.npos){
string keyword=getword(line,pos);
node bucket(keyword,id);
bucket.addentry(entry);
uniquekeywords.insert(bucket);
}
}
}
这里是hashtable insert实现的sn-p:
struct node{
string keyword;
vector<file> entries;
int origin;
void addentry(file entry);
node(string keyword, int origin);
};
void hashtable::insert(node bucket){
int key=hashfunction(bucket.keyword);
if (table[key].empty()){
table[key].push_back(bucket);
numelt++;
}
else{
vector<node>::iterator it;
it=table[key].begin();
while(it!=table[key].end()){
if (compare((*it).keyword,bucket.keyword)==0 && (*it).origin!=bucket.origin){
(*it).entries.insert((*it).entries.end(),bucket.entries.begin(),bucket.entries.end());
(*it).origin=bucket.origin;
return;
}
it++;
}
node bucketcopy(bucket.keyword,bucket.origin);
table[key].push_back(bucket);
numelt++;
return;
}
}
【问题讨论】:
-
能否请您发布您的代码?描述你认为你在做什么通常不如发布实际代码有用,尤其是在涉及算法问题时。
-
对不起,它有点损坏。我不想把整件事都贴在这里。有多个文件。但这是重要的东西。
-
您为什么要这样做而不是使用
std::map或非标准的hash_map或boost::unordered_map? -
您发布的代码不包含对
stable_sort的调用。
标签: c++ struct hashtable stable-sort