如何让我的插入函数与我的结构体一起工作?

huangapple go评论66阅读模式
英文:

Honestly lost, how do I make my insert function work with my struct?

问题

UPDATE: 错误仍然在上午11:30 PST发生

分配的任务提示如下:
A6

此任务的主要焦点是链接散列和模板函数与类。教材的第1章到第12章的内容可以帮助你很大程度上。你可以从第12章获取有关实现此任务的很多有用信息。

你可以为此任务添加任意数量的参数、函数和类,并使用你学到的任何高级技巧。但是,至少需要有两个.h文件、两个模板文件和一个.cpp文件才能生成预期的结果。

在第12.2章到12.4章中讨论了散列的概念和实现。在这个任务中,我们将实现链表(散列表的数据结构)。

一些信息
你需要知道或编写的文件:

  1. table2.h:此任务的Table类的头文件。这是一个模板类。模板参数称为RecordType,可以实例化为包含名为key的整数成员变量的任何结构或类。Table类的定义、一些有用的函数和变量如下。
    a. Table:这个类是一个记录表的容器模板类。RecordType模板参数是Table中记录的数据类型。它可以是具有默认构造函数、复制构造函数、赋值运算符和名为key的整数成员变量的任何类型。在Table模板类中,可以使用赋值和复制构造函数与Table对象一起使用。如果动态内存不足,那么复制构造函数、插入、赋值运算符可以添加新的内存。

b. Table模板类的构造函数:
Table()
后置条件:表已初始化为空表。

c. Table类的修改成员函数:

  1. void insert(const RecordType& entry)
    先决条件:entry >= 0。如果entry不是表中的关键字,则表中必须有另一个记录的空间(即,size() < CAPACITY)。
    后置条件:如果表中已经有一个关键字等于entry的记录,则该记录将被entry替换。否则,entry将作为表的新记录添加。

  2. void remove(int key)
    后置条件:如果表中有指定关键字的记录,则该记录已被删除;否则表不变。

  3. void print(int index) const;
    后置条件:如果索引处的表有数据,则以链接格式打印索引和数据。

d. Table类的常量成员函数:

  1. bool is_present(const RecordType & target) const
    后置条件:如果表中有指定关键字的记录,则返回值为true。否则返回值为false。

  2. void find(int key, bool& found, RecordType& result) const
    后置条件:如果表中有指定关键字的记录,则found为true,result设置为具有该关键字的记录的副本。否则,found为false,result包含垃圾值。

  3. size_t size() const
    后置条件:返回表中记录的总数。
    e. 私有数据成员:

  4. Node* data[TABLE_SIZE];

  5. size_t total_records;
    // 辅助函数

  6. size_t hash(int key) const;

  7. Node* find_node(Node& cursor, Node& precursor, int key) const;

  8. table2.template:是table2.h的实现文件。

  9. link2.h是一个头文件,提供了一个用于操作链表的十个模板函数工具包。列表的每个节点包含一段数据和指向下一个节点的指针(已提供)。

  10. link2.template是link2.h的实现文件。

  11. CISP430V4A6.cpp是此任务的驱动程序,需要执行多个步骤来测试程序。
    a. 实例化两个Table对象,每个对象有10个字段。
    b. 显示两个Table对象的信息。
    c. 使用随机数生成器生成70个数字,每个数字在0~200之间,用于Table对象。
    d. 显示两个Table对象的信息。
    e. 删除第一个对象中的所有数据。
    f. 显示两个Table对象的信息。
    g. 使用等号将第二个对象分配给第一个对象。
    h. 显示两个Table对象的信息。

收到的错误:

严重性代码描述项目文件行抑制状态
错误C2664'void CISP430_A6::Table::insert(const CISP430_A6::Table::RecordType &)': 无法将参数1从'size_t'转换为'const CISP430_A6::Table::RecordType &'CISP430_A6v4C:\Users\kater\OneDrive\Desktop\CISP430_A6v4\CISP430_A6v4\table2driver.cpp25

驱动程序文件:

#include <iostream>
#include <cstdlib> // for rand and srand
#include <ctime> // for time
#include "table2.h"
#include "link2.h"

using namespace std;
using namespace CISP430_A6;
int main() {
    srand(time(nullptr)); // seed the random number generator with the current time
    Table<size_t> table1;
    //Table<int> table2;
  
    cout << "Initial state of table1:\n";
    for (int i = 0; i < Table<int>::TABLE_SIZE; ++i) {
        table1.print(i); // this works
    }
    /*cout << "Initial state of table2:\n";
    for (size_t i = 0; i < Table<int>::TABLE_SIZE; ++i) {
        table2.print(i);
    }*/
    //cout << "Generating random numbers...\n";
    for (int i = 0; i < 70; ++i) {
        size_t number = rand() % 201; // generate a random number between 0 and 200
        table1.insert(number); // This will not work
        //table2.insert(number);
    }
    cout << "State of table1 after inserting 70 random numbers:\n";
    for (size_t i = 0; i < Table<int>::TABLE_SIZE; ++i) {
        table1.print(i);
    }
  
    return 0;
}

头文件:

#ifndef TABLE2_H
#define TABLE2_H


<details>
<summary>英文:</summary>

UPDATE: Errors still occuring 11:30 AM PST
Assignment prompt below:
A6

The main focus of this assignment is chained hash and template functions and class.  .   The material from Ch1 ~ 12 of the textbook can help you tremendously. You can get a lot of good information about implementing this assignment from chapter 12.  

You can add any number of paramours, functions and classes for this assignment and use any advance skills you learned.  But there need to have at least two .h files, two template files and one .cpp file to generate the expecting result.

In sections 12.2 ~ 12.4 discuss the hashing concept and implementation.  This assignment we will implement a chaining (data structure of a hash table).

Some information
Files that you need to know or write: 
1.	table2.h: A header file for this assignment’s Table class.  This is a template class. The template parameter, called RecordType, may be instantiated as any struct or class that contains an integer member variable called key. 
The following are definition of a Table class, some useful functions and variables.
a.	Table&lt;RecordType&gt;
This class is a container template class for a Table of records. The template parameter, RecordType, is the data type of the records in the Table. It may any type with a default constructor, a copy constructor,an assignment operator, and an integer member variable called key.  In the Table&lt;RecordType&gt; template class assignments and the copy constructor may be used with Table objects.  If there is insufficient dynamic memory, then the copy constructor, insert, the assignment operator can add new memory. 

b.	 CONSTRUCTOR for the Table&lt;RecordType&gt; template class:
  Table( )
  Postcondition: The Table has been initialized as an empty Table.

c.	 MODIFICATION MEMBER FUNCTIONS for the Table&lt;RecordType&gt; class:
1. void insert(const RecordType&amp; entry)
  Precondition: entry&gt;= 0. Also if entry is not already a key in the table, then the Table has space for another record.   (i.e., size( ) &lt; CAPACITY).
 Postcondition: If the table already had a record with a key equal to entry, then that record is replaced by entry. Otherwise, the entry will be added as a new record of the Table.

2.  void remove(int key)
Postcondition: If a record was in the Table with the specified key, then that record has been removed; otherwise the table is unchanged.

3.  void print(int index)const;
Postcondition: If the Table with the index has data, then print the index and data in a chining format

d. CONSTANT MEMBER FUNCTIONS for the Table&lt;RecordType&gt; class:
1. bool is_present(const RecordType &amp; target) const
Postcondition: The return value is true if there is a record in the Table with the specified key. Otherwise, the return value is false.

2.  void find(int key, bool&amp; found, RecordType&amp; result) const
  Postcondition: If a record is in the Table with the specified key, then found is true and result is set to a copy of the record with that key.  Otherwise found is false and the result contains garbage.

3.  size_t size( ) const
  Postcondition: Return value is the total number of records in the Table.
e.	Private data members:
1.	        Node&lt;RecordType&gt; *data[TABLE_SIZE];
2.	        size_t total_records;
        // HELPER FUNCTION
3.	        size_t hash(int key) const;
4.	        Node&lt;RecordType&gt;* find_node(Node&lt;RecordType&gt; *&amp;cursor,Node&lt;RecordType&gt; *&amp;precursor, int key) const;

2.	table2.template: is the implementation file for the table2.h.

3.	 link2.h is a header file to provide a toolkit of ten template functions for manipulating linked lists.  Each node of the list contains a piece of data and a pointer to the next node (provided).

4.	link2.template is the implementation file for the linke.h (provided). 

5.	CISP430V4A6.cpp is the driver for this assignment and there are several steps you need to do to test the program.
a.	Instantiate two Table objects and each with 10 fields. 
b.	Display the two Table objects’ information.
c.	Use random number generator to generate 70 numbers each in between 0~200 for the Table objects.
d.	 Display the two Table objects’ information.
e.	Removes all the data in first object.
f.	Display the two Table objects’ information.
g.	Using = to assign 2nd object to the first one.
h.	 Display the two Table objects’ information.

Errors recieved: 

Severity	Code	Description	Project	File	Line	Suppression State
Error	C2664	&#39;void CISP430_A6::Table&lt;int&gt;::insert(const CISP430_A6::Table&lt;int&gt;::RecordType &amp;)&#39;: cannot convert argument 1 from &#39;size_t&#39; to &#39;const CISP430_A6::Table&lt;int&gt;::RecordType &amp;&#39;	CISP430_A6v4	C:\Users\kater\OneDrive\Desktop\CISP430_A6v4\CISP430_A6v4\table2driver.cpp	25

Driver file:	

#include <iostream>
#include <cstdlib> // for rand and srand
#include <ctime> // for time
#include "table2.h"
#include "link2.h"

using namespace std;
using namespace CISP430_A6;
int main() {
srand(time(nullptr)); // seed the random number generator with the current time
Table<size_t> table1;
//Table<int> table2;

cout &lt;&lt; &quot;Initial state of table1:\n&quot;;
for (int i = 0; i &lt; Table&lt;int&gt;::TABLE_SIZE; ++i) {
    table1.print(i); // this works
}
/*cout &lt;&lt; &quot;Initial state of table2:\n&quot;;
for (size_t i = 0; i &lt; Table&lt;int&gt;::TABLE_SIZE; ++i) {
    table2.print(i);
}*/
//cout &lt;&lt; &quot;Generating random numbers...\n&quot;;
for (int i = 0; i &lt; 70; ++i) {
    size_t number = rand() % 201; // generate a random number between 0 and 200
    table1.insert(number); // This will not work
    //table2.insert(number);
}
cout &lt;&lt; &quot;State of table1 after inserting 70 random numbers:\n&quot;;
for (size_t i = 0; i &lt; Table&lt;int&gt;::TABLE_SIZE; ++i) {
    table1.print(i);
}

return 0;

}

Header File

#ifndef TABLE2_H
#define TABLE2_H
#include <cstdlib> // Provides size_t
#include <list>
#include "link2.h"
using namespace std;

namespace CISP430_A6
{

template &lt;class RecordType&gt; class Table
{
public:
	
	//RecordType entry;
	// MEMBER CONSTANT
	static const size_t TABLE_SIZE = 10;
	struct RecordType{ int key = 0; } entry;
	// CONSTRUCTOR AND DESTRUCTOR
	Table();
	Table(const Table&amp; source);
	~Table();
	// MODIFICATION MEMBER FUNCTIONS
	void insert(const RecordType&amp; entry);
	void remove(int key);
	void print(int index);
	void operator =(const Table&amp; source);
	// CONSTANT MEMBER FUNCTIONS
	void find(int key, bool&amp; found, RecordType&amp; result) const;
	bool is_present(const RecordType&amp; target) const;
	size_t size() const { return total_records; };
private:
	Node&lt;RecordType&gt;* data[TABLE_SIZE];
	size_t total_records;
	// HELPER MEMBER FUNCTION
	size_t hash(int entry) const;
	Node&lt;RecordType&gt;* find_node(Node&lt;RecordType&gt;*&amp; cursor, Node&lt;RecordType&gt;*&amp; precursor, int  key) const;

};

}
#include "table2.template"
#endif

Insert function with other things:
    template &lt;class RecordType&gt;
Table&lt;RecordType&gt;::Table()
{
	//Class constructor: Constructs an empty table.

	for (size_t i = 0; i &lt; TABLE_SIZE; ++i)
	{
		data[i] = NULL;
	}

	total_records = 0;
}

template &lt;class RecordType&gt;
Table&lt;RecordType&gt;::Table(const Table&amp; source)
{
	// Copy constructor: Creates a copy of the con
	for (int i = 0; i &lt; TABLE_SIZE; ++i)
	{
		Node&lt;RecordType&gt;* tail_ptr;
		list_copy(source.data[i], data[i], tail_ptr);
	}

	total_records = source.total_records;
}

template &lt;class RecordType&gt;
Table&lt;RecordType&gt;::~Table()
{
	// Table destructor.
	for (int i = 0; i &lt; TABLE_SIZE; ++i)
	{
		if (data[i] != NULL)
		{
			list_clear(data[i]);
		}
	}

	total_records = 0;
}
template&lt;class RecordType&gt;
void Table&lt;RecordType&gt;::operator=(const Table&amp; source)
{
	if (this != &amp;source)
	{
		for (int i = 0; i &lt; TABLE_SIZE; ++i)
		{
			Node&lt;RecordType&gt;* tail_ptr;
			list_copy(source.data[i], data[i], tail_ptr);
		}
		total_records = source.total_records;
	}
}
template&lt;class RecordType&gt;
void Table&lt;RecordType&gt;::print(int index)
{
	Node&lt;RecordType&gt;* curNode = data[index];
	cout &lt;&lt; &quot;[( &quot; &lt;&lt; index &lt;&lt; &quot; )]----&gt; &quot;;
	if (data[index] != NULL)
	{
		while (curNode != NULL)
		{
			cout &lt;&lt; &quot;[&quot; &lt;&lt; data[index] &lt;&lt; &quot;]--&gt;&quot;;
		}
	}
	else if ((data[index] == NULL) || (curNode == NULL))
	{
		cout &lt;&lt; &quot; NULL &quot;;
	}
	cout &lt;&lt; endl;
}
    template&lt;class RecordType&gt;
void Table&lt;RecordType&gt;::insert(const RecordType&amp; entry)
{	// Precondition: entry &gt;= 0 and there is space for another record 
	assert(entry.key &gt;= 0 &amp;&amp; total_records &lt; TABLE_SIZE); 
	// Calculate the index in the array where the entry should be inserted 
	size_t index = hash(entry.key); 
	// Search for the entry in the linked list at the index 
	Node&lt;RecordType&gt;* cursor = list_search(data[index], entry.key); 
	// If the entry is found, replace it 
	if (cursor != nullptr) 
	{ 
		cursor-&gt;data = entry; 
	} // Otherwise, insert the entry at the beginning of the list 
	else 
	{ 
		list_head_insert(data[index], entry); 
		total_records++; 
	}
}
This is for a chained hashing assignment and the functions called in insert are prewritten and part of a linked list toolkit.


I am expecting print to print the newly inserted values from the driver file. 

</details>


# 答案1
**得分**: 1

以下是已翻译的内容:

从问题描述中很明显知道了需要什么。类似这样的结构:

struct MyRecord
{
int key = 0;
};

int main()
{
Table table;
...
}


因此,在模板类之外声明了一个类型(在上面的代码中称为`MyRecord`),然后在声明表时将该类型用作参数`Table<MyRecord> table;`

同时,请不要忘记从类`Table`中删除`struct RecordType { ... };`。这显然是您根据对模板的工作方式的误解添加的。

问题描述中没有提到您需要有两个不同的`RecordType`定义。`RecordType`的唯一提到是作为`Table`类中的模板参数。

这就像函数参数的情况一样。函数参数有一个名称,但这并不意味着您必须使用具有相同名称的变量调用该函数。因此,对于模板参数,它有一个名称,但当您*实例化*模板时,可以提供一个完全不同名称的类型。

不幸的是,这些更改意味着您基本上必须重新开始这个任务。

<details>
<summary>英文:</summary>

It&#39;s clear from the problem description what is required. Something like this

    struct MyRecord
    {
        int key = 0;
    };
    
    int main()
    {
        Table&lt;MyRecord&gt; table;
        ...
    }

So a type is declared outside of the template class (called `MyRecord` in the code above) and then that type is used as a parameter when the table is declared `Table&lt;MyRecord&gt; table;`

And also don&#39;t forget to remove `struct RecordType { ... };` from class `Table`. That was clearly your addition based on a misunderstanding of how templates work.

There&#39;s nothing in the problem description that says you need to have two different `RecordType` definitions. The only mention of `RecordType` is as the template parameter in the `Table` class.

This is just like the situation with function parameters. A function parameter has some name, but that does not mean that you must call that function with a variable that has the same name. So with a template parameter, it has a name, but when you *instantiate* the template you can supply a type with a completely different name.

Unfortunately these changes do mean that you basically have to start again with this assignment.


</details>



huangapple
  • 本文由 发表于 2023年4月17日 01:48:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定