我正在实现自己的哈希表,我遇到了以下问题:当我将节点插入表中时,当我循环遍历数组时,它们不会打印出来。我使用数组数组作为底层数据结构,逻辑如下:
就像我之前说的那样,问题是数据被正确地输入到数组中(我用print语句检查过),但是当我打印数组时,没有输出任何内容。我还检查了我的对象是否正确构造(再次,使用print语句),但一切看起来都很好。我已经在下面提供了完整的代码。任何帮助将不胜感激!
public class UnitTest
{
private string dbConnectionString = "DbConnectionStringOrConnectionName";
public EFTimestampBug.Models.Context CreateContext()
{
var options = new DbContextOptionsBuilder();
options.UseSqlServer(dbConnectionString);
return new EFTimestampBug.Models.Context(options.Options);
}
[Fact] // this test passes
public async Task TimestampChangedExternally()
{
using (var db = CreateContext())
{
var person = await db.Persons.SingleAsync(x => x.Id == 1);
person.Title = "Update 2 - should fail";
// update the database manually after we have a person instance
using (var connection = new System.Data.SqlClient.SqlConnection(dbConnectionString))
{
var command = connection.CreateCommand();
command.CommandText = "update person set title = 'changed title' where id = 1";
connection.Open();
await command.ExecuteNonQueryAsync();
command.Dispose();
}
// should throw exception
try
{
await db.SaveChangesAsync();
throw new Exception("should have thrown exception");
}
catch (DbUpdateConcurrencyException)
{
}
}
}
[Fact]
public async Task EmulateAspPostbackWhereTimestampHadBeenChanged()
{
using (var db = CreateContext())
{
var person = await db.Persons.SingleAsync(x => x.Id == 1);
person.Title = "Update 2 - should fail " + DateTime.Now.Second.ToString();
// This emulates post back where the timestamp is passed in from the web page
// the Person entity attached dbcontext does have the latest timestamp value but
// it needs to be changed to what was posted
// this way the user would see that something has changed between the time that their screen initially loaded and the time they posted the form back
var passedInTimestamp = new byte[] { 0, 0, 0, 0, 0, 0, 0, 120 }; // a hard coded value but normally included in a postback
//person.Timestamp = passedInTimestamp;
var entry = db.Entry(person).Property(u => u.Timestamp);
entry.OriginalValue = passedInTimestamp;
try
{
await db.SaveChangesAsync(); // EF ignores the set Timestamp value and uses its own value in the outputed sql
throw new Exception("should have thrown DbUpdateConcurrencyException");
}
catch (DbUpdateConcurrencyException)
{
}
}
}
}
答案 0 :(得分:2)
这一行的c
函数中存在一个错误:
insert(Node<T> Node)
auto location=hashTable.at(hashValue);
//...
location.at(index) = Node;
应该是引用而不是副本。发生的事情是您正在更改本地location
,而不是哈希表使用的实际location
。因此,没有任何改变“坚持”。
以上一行应为:
location
现在,您要将返回的引用分配给引用。
此外,我强烈建议您使用调试器,因为如果您逐步执行代码以查看正在执行的操作,则可以轻松诊断此错误。
答案 1 :(得分:0)
在HashTable::insert
这一行:
auto location = hashTable.at(hashValue);
制作Node
的副本。然后,您可以在副本中操作并存储,而不是hashTable
中的节点。参考节点
auto & location = hashTable.at(hashValue);
应该修复它。