病媒没有正常繁殖
Vector not populating properly
我试图找出在使用线性探测公式(h(k) = k%T其中T是表大小)的指定大小的哈希表中发生碰撞之前插入的平均次数。我做了100个"实验"来计算碰撞前的平均插入次数。下面是我为一个大小为23的表编写的代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;
int main()
{
int sizeArray[7] = { 7, 11, 13, 17, 19, 23, 29 }; // ignore for now
double resultArray[7] = { 0 }; // ignore for now
vector<double> hashNumVec; // stores hash keys
int hashValue = 0;
int count = 0;
double average;
vector<double> resultVec;
int randNum;
srand(time(NULL));
for (int k = 0; k < 100; k++){ // 100 experiments
randNum = rand() % 100 + 1; // generate random number
hashValue = (randNum) % 23; // hash value for T = 23
vector<double>::iterator it;
it = find(hashNumVec.begin(), hashNumVec.end(), hashValue);
if (it == hashNumVec.end()){ //no collision
count++;
hashNumVec.push_back(hashValue);
}
else
{
resultVec.push_back(count); // add the amount of insertions to vector
break;
}
}
for (auto i = resultVec.begin(); i != resultVec.end(); ++i)
cout << *i << ' ';
return 0;
}
我希望我的向量填充100个值。它们中的每一个都是导致碰撞的插入次数的计数值。然而,当我把它打印出来的时候,它只显示向量中有一个值。我做错了什么?
EDIT:我只是想存储每次碰撞需要多少插入。比如说第一次它在碰撞前插入了6次然后在碰撞前插入了5次,在碰撞前插入了4次。等等,我想让向量读取6 5 4 ...
这是因为代码:
{
resultVec.push_back(count); // add the amount of insertions to vector
break;
}
在第一次检测到碰撞时打破for
循环。所以你在resultVec
中只有一个值被显示。
编辑
我希望我的向量填充100个值。
当前代码不会这样做。随机化并创建一个包含100个值的散列。然后,当检测到碰撞时,仅将碰撞计数器存储在resultVec
中。100次随机化中发生100次碰撞的概率为0。
将break;
替换为count=0;
。它将打印碰撞之间的插入次数。换句话说,在下一次碰撞发生之前,没有碰撞的插入有多少次。
EDIT2
如果您正在寻找第一个碰撞之前的插入数量,那么您需要将break
替换为
count = 0;
hashNumVec.clear();
您需要清除哈希向量以及计数器,因为在每次碰撞之后,您希望从头开始测量(否则计数器将显示第二次碰撞之前的插入数量,然后是第三次,等等…)
程序检查在100次插入中是否发生冲突。它不会做100次试验来计算实现碰撞需要多少次插入。为此,您需要第二个循环:
for (int k = 0; k < 100; k++){ // 100 experiments
for(;;) { // Each experiment continues until the "break" statement in your else clause.
// The loop body, exactly as you currently have it written.
}
count = 0; // Reset for the next experiment!
}
相关文章:
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- C 和 C++ 中开关语句的案例标签的常量值,但显示不同的行为
- 为什么我们将单个或多维数组的大小声明为常量值?
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- const_cast静态数组以添加恒常性
- 函数调用在常量表达式中必须具有常量值
- 自动模板参数、数据成员和恒常性
- 有没有办法检测自身内部的类恒常性?
- 在C++中更新常量变量值
- 表达式必须具有常量值
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- 为什么const_cast删除指针的恒常性,而不删除指向常量的指针的恒常性?
- 在C++中创建一个具有常量值的向量
- 对指针和恒常性兼容性的引用
- 无法赋值,因为函数'operator[]'返回常量值
- C++表达式必须具有常数值
- 表达式必须具有常数值,变量不能用作定义数组大小的常数
- NAN繁殖和IEEE 754标准
- 如何在C 中以自己的100次以上的数量繁殖
- 病媒没有正常繁殖