c++ 中的设置函数不起作用
Set function in c++ not working
我正在用 C++ 编写一个 Set class(我知道已经有一个库,这是一个赋值)并且与 C++ 中的类似,我正在编写一个函数来检查输入的条目是否已经在集合
void Set::insert(const Set::value_type& entry)
{
for (int i=0; i<used;i++)
{
if(data[i]!=entry && used<CAPACITY)
{
data[used] = entry;
used++;
}
else
{
throw "Out of capacity in Set and Intger already in Set";
}
}
}
函数的作用是查看数字是否在集合中。如果该号码不在集合中并且已使用 < 容量(意味着它们还有空间),则插入该号码。当我使用插入功能时,什么也没有发生。有人可以帮帮我吗?也许我以错误的方式接近这个。
如所写,当 insert
-ing 为空 Set
时,used
将为 0,因此循环终止而不做任何事情。您不处理循环后未找到值的情况,因此它永远不会插入。
即使您切换到循环 CAPACITY
,内部检查也会在第一个 运行 上用相同的值填充整个 Set
(因为 if
检查的块执行,但不执行 break
循环,因此它一遍又一遍地存储相同的值,直到它填充 Set
或找到自己),然后在随后的 insert
s,它会立即引发异常。也许你想要这样的东西?
void Set::insert(const Set::value_type& entry)
{
// If you have a membership test function, you can reuse it here instead
// of including this loop, e.g.:
// if (this->contains(entry)) return;
for (int i=0; i < used;i++)
{
if (data[i] == entry) {
// value already in set, nothing to do
return;
}
}
// Not already in Set, add if we have room or raise exception
if (used < CAPACITY) {
data[used++] = entry;
return;
}
throw "Out of capacity in Set";
}
当集合最初为空时,used == 0
,您的循环不执行任何操作,因为 i < used
条件立即失败。所以你永远不会将新项目添加到集合中。
如果集合中有项目,如果新条目不同于任何现有元素,循环会将其添加到集合中。它为每个不等于的元素重复添加它。
您需要做的是遍历整个集合,看看是否在任何地方都找到了匹配项。如果它在整个循环中都没有找到匹配项,它就会添加新条目。
void Set::insert(const Set::value_type& entry)
{
for (int i=0; i<used;i++)
{
if(data[i] ==entry)
{
return;
}
}
// Not found, add it
if (used < CAPACITY) {
data[used++] = entry;
} else
{
throw "Out of capacity in Set";
}
}
我正在用 C++ 编写一个 Set class(我知道已经有一个库,这是一个赋值)并且与 C++ 中的类似,我正在编写一个函数来检查输入的条目是否已经在集合
void Set::insert(const Set::value_type& entry)
{
for (int i=0; i<used;i++)
{
if(data[i]!=entry && used<CAPACITY)
{
data[used] = entry;
used++;
}
else
{
throw "Out of capacity in Set and Intger already in Set";
}
}
}
函数的作用是查看数字是否在集合中。如果该号码不在集合中并且已使用 < 容量(意味着它们还有空间),则插入该号码。当我使用插入功能时,什么也没有发生。有人可以帮帮我吗?也许我以错误的方式接近这个。
如所写,当 insert
-ing 为空 Set
时,used
将为 0,因此循环终止而不做任何事情。您不处理循环后未找到值的情况,因此它永远不会插入。
即使您切换到循环 CAPACITY
,内部检查也会在第一个 运行 上用相同的值填充整个 Set
(因为 if
检查的块执行,但不执行 break
循环,因此它一遍又一遍地存储相同的值,直到它填充 Set
或找到自己),然后在随后的 insert
s,它会立即引发异常。也许你想要这样的东西?
void Set::insert(const Set::value_type& entry)
{
// If you have a membership test function, you can reuse it here instead
// of including this loop, e.g.:
// if (this->contains(entry)) return;
for (int i=0; i < used;i++)
{
if (data[i] == entry) {
// value already in set, nothing to do
return;
}
}
// Not already in Set, add if we have room or raise exception
if (used < CAPACITY) {
data[used++] = entry;
return;
}
throw "Out of capacity in Set";
}
当集合最初为空时,used == 0
,您的循环不执行任何操作,因为 i < used
条件立即失败。所以你永远不会将新项目添加到集合中。
如果集合中有项目,如果新条目不同于任何现有元素,循环会将其添加到集合中。它为每个不等于的元素重复添加它。
您需要做的是遍历整个集合,看看是否在任何地方都找到了匹配项。如果它在整个循环中都没有找到匹配项,它就会添加新条目。
void Set::insert(const Set::value_type& entry)
{
for (int i=0; i<used;i++)
{
if(data[i] ==entry)
{
return;
}
}
// Not found, add it
if (used < CAPACITY) {
data[used++] = entry;
} else
{
throw "Out of capacity in Set";
}
}