c ++设置插入号检查重复项
c++ Set insertion numbers check for duplicates
我的作业是写一组 class。
首先,我有一个节点 class,它具有
的功能
void list_head_insert(node<Item>*& head_ptr, const Item& entry)
{
head_ptr = new node<Item>(entry, head_ptr);
}
这会在开头插入一个节点
我有两个设置函数,第一个检查插入的数字是否存在。如果它这样做 returns true 如果它不这样做 returns false.
template <class Item>
bool set<Item>::contains(const Item& target)
{
while(head_ptr->data()!=target&&head_ptr->link()!=NULL)
head_ptr=head_ptr->link();
if(head_ptr->data()==target)
{
return true;
}
else
{
return false;
}
}
第二个set函数使用list_head_insert
函数插入节点
template <class Item>
void set<Item>::insert(const Item& entry)
// Library facilities used: node2.h
{
if(contains(entry) !=true)
{
list_head_insert(head_ptr, entry);//inserts node
++many_nodes;//increases the number of items
}
}
最后我有一个打印功能
void print(set<int>bagints)
{
for(bag<int>::iterator cursor = bagints.begin(); cursor != bagints.end(); ++cursor)
{
cout<<*cursor<< " ";
}
}
当我插入数字示例列表 Mylist.insert(10)
...等并尝试打印数字时,它不会打印出来。我检查了 contains 功能,它工作正常。我认为问题出在插件中,但我不知道为什么。
最初,您的新集合是空的。当您尝试插入第一个元素时,您的代码将通过调用 set<Item>::contains()
检查它是否已经存在。
此时,head_ptr
仍然是NULL
,(假设您在构建空集时已经正确初始化了它)。在 set<Item>::contains()
的 while 条件下,不幸的是,您通过执行 head_ptr->data()
取消了对 NULL 指针的引用。这是未定义的行为:
- 在最好的情况下,您的代码会出现段错误,并且您的代码不会执行任何其他操作。并且不打印任何东西!
- 在其他情况下,您的函数可能最终返回任何内容,包括 true,从而使您的代码相信没有任何内容可插入。
另请注意,如果您设法在集合中插入任何内容,则下次调用 contain()
时,您将更改 head_ptr
以指向最后一个节点。 .
重写你的函数set<Item>::contains()
:
{
for (auto p=head_ptr; p; p = p->link() )
if(p->data()==target)
{
return true;
}
return false;
}
我的作业是写一组 class。 首先,我有一个节点 class,它具有
的功能void list_head_insert(node<Item>*& head_ptr, const Item& entry)
{
head_ptr = new node<Item>(entry, head_ptr);
}
这会在开头插入一个节点
我有两个设置函数,第一个检查插入的数字是否存在。如果它这样做 returns true 如果它不这样做 returns false.
template <class Item>
bool set<Item>::contains(const Item& target)
{
while(head_ptr->data()!=target&&head_ptr->link()!=NULL)
head_ptr=head_ptr->link();
if(head_ptr->data()==target)
{
return true;
}
else
{
return false;
}
}
第二个set函数使用list_head_insert
函数插入节点
template <class Item>
void set<Item>::insert(const Item& entry)
// Library facilities used: node2.h
{
if(contains(entry) !=true)
{
list_head_insert(head_ptr, entry);//inserts node
++many_nodes;//increases the number of items
}
}
最后我有一个打印功能
void print(set<int>bagints)
{
for(bag<int>::iterator cursor = bagints.begin(); cursor != bagints.end(); ++cursor)
{
cout<<*cursor<< " ";
}
}
当我插入数字示例列表 Mylist.insert(10)
...等并尝试打印数字时,它不会打印出来。我检查了 contains 功能,它工作正常。我认为问题出在插件中,但我不知道为什么。
最初,您的新集合是空的。当您尝试插入第一个元素时,您的代码将通过调用 set<Item>::contains()
检查它是否已经存在。
此时,head_ptr
仍然是NULL
,(假设您在构建空集时已经正确初始化了它)。在 set<Item>::contains()
的 while 条件下,不幸的是,您通过执行 head_ptr->data()
取消了对 NULL 指针的引用。这是未定义的行为:
- 在最好的情况下,您的代码会出现段错误,并且您的代码不会执行任何其他操作。并且不打印任何东西!
- 在其他情况下,您的函数可能最终返回任何内容,包括 true,从而使您的代码相信没有任何内容可插入。
另请注意,如果您设法在集合中插入任何内容,则下次调用 contain()
时,您将更改 head_ptr
以指向最后一个节点。 .
重写你的函数set<Item>::contains()
:
{
for (auto p=head_ptr; p; p = p->link() )
if(p->data()==target)
{
return true;
}
return false;
}