Постановка задачи:
Реализация работы со справочником предметной области “Магазин”( с ключами Артикул, Наименование товара, ИНН поставщика, Дата) с использованием структур данных АВЛ-дерево (по нему распределяем по ключу Наименование товара), состоящее из хеш-таблиц (по ним распределяем по ключу Дата).
Общие требования:
Оконный интерфейс (в среде разработки WinForms, но исходная реализация на C++)
Нельзя использовать универсальные классы-коллекции в System.Collections для реализации заданных структур данных
В интерфейсе отображать справочник в табличном виде и окно отладки для вывода структур данных
Какой должен быть функционал:
Возможность задания в интерфейсе первоначального размера ХТ
Работа со справочником:
загрузка из текстового файла / сохранение в текстовый файл
добавление
удаление
поиск
просмотр
Окно отладки (печать структур данных)
Форма использует файлы Kursovaya.cpp, MyForm.h, MyForm.cpp и hashtableform.h.
Код Kursovaya.cpp:
#include
#include
#include
#include
#include
#include
using namespace std;
struct VendorCode
{
long long int vendorcode;
bool correct = true;
VendorCode(long long int vc) {
long long int n = vc;
int c = 0;
while (n != 0) {
c++;
n /= 10;
}
if (c == 8) {
vendorcode = vc;
}
else {
correct = false;
std::cerr << "Invalid Vendor Code. Setting default Vendor Code to 10000000" << std::endl;
vendorcode = 10000000;
}
}
};
struct ProductName {
std::string productname;
ProductName(std::string pn) : productname(pn) {}
};
struct TIN
{
long long int tin;
bool correct = true;
TIN(long long int t) {
long long int n = t;
int c = 0;
while (n != 0)
{
c++;
n /= 10;
}
if (c == 10)
{
tin = t;
}
else
{
correct = false;
std::cerr << "Invalid TIN. Setting default TIN to 1000000000" << std::endl;
tin = 1000000000;
}
}
};
struct Date {
int day;
int month;
int year;
bool correct = true;
Date(int d, int m, int y) {
if (y > 2024 || y < 2000)
correct = false;
else
{
switch (m)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if (d < 1 || d > 31)
correct = false;
break;
case 4: case 6: case 9: case 11:
if (d < 1 || d > 30)
correct = false;
break;
case 2:
if (d < 1 || d > 28)
correct = false;
break;
default:
correct = false;
break;
}
}
if (correct)
{
day = d;
month = m;
year = y;
}
else
{
std::cerr << "Invalid date. Setting default date to 1.1.2000." << std::endl;
day = 1;
month = 1;
year = 2000;
}
}
};
struct Sorts {
VendorCode vendorcodes;
ProductName productnames;
TIN tins;
Date dates;
int firstHash;
Sorts(const VendorCode& vc, const ProductName& pn, const TIN& t, const Date& d) : vendorcodes(vc), productnames(pn), tins(t), dates(d), firstHash(0) {}
};
struct Cell {
Sorts sorts;
int flag;
int firstHash;
Cell() : sorts(VendorCode(0), ProductName(""), TIN(0), Date(1, 1, 2000)), flag(0), firstHash(0) {}
};
class HashTable
{
private:
int digitsCount(int n)
{
int c = 0;
while (n != 0)
{
c++;
n /= 10;
}
return c;
}
int hash1(int key1, int key2, int key3, int n)
{
int d = digitsCount(n - 1);
Assistant
User
hashTableForm->FillHashTableTable(pn); невозможно с таким аргументом
Assistant
int l = digitsCount(key1);
int e = (2 * l - d) / 2;
int r = pow(10, e);
int h1 = (key1 * key1) / r;
int mod = pow(10, d);
h1 %= mod;
l = digitsCount(key2);
e = (2 * l - d) / 2;
r = pow(10, e);
int h2 = (key2 * key2) / r;
mod = pow(10, d);
h2 %= mod;
l = digitsCount(key3);
e = (2 * l - d) / 2;
r = pow(10, e);
int h3 = (key3 * key3) / r;
mod = pow(10, d);
h3 %= mod;
int h = (h1 + h2 + h3) % n;
return h;
}
int hash2(int key1, int key2, int key3, int j, int k, int n)
{
int hash = (hash1(key1, key2, key3, n) + j * k) % n;
return hash;
}
int collisionInsert(int key1, int key2, int key3, int n, int hash)
{
int h = hash;
int j = 0;
int k = 3;
do
{
if (table[h].sorts.dates.day == key1 && table[h].sorts.dates.month == key2 && table[h].sorts.dates.year == key3)
return -2;
if (table[h].flag != 1)
{
return h;
}
else
{
h = hash2(key1, key2, key3, j, k, n);
++j;
}
} while (j != n);
return -1;
}
int collisionSearch(int key1, int key2, int key3, int n, int hash)
{
int h = hash;
int j = 0;
int k = 3;
do
{
if (table[h].sorts.dates.day == key1 && table[h].sorts.dates.month == key2 && table[h].sorts.dates.year == key3)
{
return h;
}
else
{
h = hash2(key1, key2, key3, j, k, n);
++j;
}
} while (j != n);
return -1;
}
public:
std::vector table;
bool isEmpty()
{
for (int i = 0; i < table.size(); i++)
{
if (table[i].flag == 1)
return false;
}
return true;
}
int insertItem(Sorts s)
{
int n = table.size();
int key1 = s.dates.day;
int key2 = s.dates.month;
int key3 = s.dates.year;
int hash = hash1(key1, key2, key3, n);
s.firstHash = hash;
if (table[hash].flag != 1)
{
table[hash].sorts = s;
table[hash].firstHash = s.firstHash;
table[hash].flag = 1;
return 0;
}
else
{
int secondhash = collisionInsert(key1, key2, key3, n, hash);
if (secondhash == -2)
{
std::cout << "Item is already in the table." << std::endl;
return -2;
}
else if (secondhash == -1)
{
std::cout << "Can't insert, table is full." << std::endl;
return -1;
}
else
{
for (int i = 0; i < table.size(); i++)
{
if (table[i].sorts.dates.day == key1 && table[i].sorts.dates.month == key2 && table[i].sorts.dates.year == key3)
return -2;
}
table[secondhash].sorts = s;
table[secondhash].firstHash = s.firstHash;
table[secondhash].flag = 1;
return 1;
}
}
}
int removeItem(int key1, int key2, int key3)
{
int n = table.size();
int hash = hash1(key1, key2, key3, n);
if (table[hash].sorts.dates.day == key1 && table[hash].sorts.dates.month == key2 && table[hash].sorts.dates.year == key3)
{
table[hash].flag = 2;
std::cout << "Removed" << std::endl;
return 0;
}
else
{
int secondhash = collisionSearch(key1, key2, key3, n, hash);
if (secondhash != -1)
{
if (table[secondhash].flag == 1)
{
table[secondhash].flag = 2;
std::cout << "Removed" << std::endl;
return 1;
}
}
std::cout << "Item is not in the table." << std::endl;
return -1;
}
}
HashTable()
{
bool isEmpty()
{
if (root == NULL)
return true;
else
return false;
}
void addItem(long long int vc, std::string pn, long long int t, int d, int m, int y)
{
bool h = false;
add(vc, pn, t, d, m, y, root, h);
}
void removeItem(std::string pn, int d, int m, int y)
{
bool h = false;
delet(pn, d, m, y, root, h);
}
int searchItem(std::string pn, int d, int m, int y)
{
bool h = false;
int searchsteps = 0;
searchsteps = search(pn, d, m, y, root, h, searchsteps); // Если не найден, то -1
return searchsteps;
}
void printTree()
{
print(root, 0);
}
void writeFile()
{
std::ofstream out("OutputFile.txt");
walk(root, 0, out);
}
Tree(){}
for (int i = 0; i < sorts.size(); i++)
{
if (i < sorts.size())
addItem(sorts[i].vendorcodes.vendorcode, sorts[i].productnames.productname, sorts[i].tins.tin, sorts[i].dates.day, sorts[i].dates.month, sorts[i].dates.year);
}
}
};
Код MyForm.h:
#pragma once
#include "HashTableForm.h"
namespace KursovayaCLR {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Сводка для MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
Tree* GetTree()
{
return tree; // где tree - указатель на дерево в MyForm
}
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
tree = new Tree();
hashTableForm = gcnew HashTableForm(GetTree());
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
delete tree;
}
}
private: System::Windows::Forms::Button^ btnAdd;
protected:
private: System::Windows::Forms::Button^ btnRemove;
private: System::Windows::Forms::TextBox^ textBoxHTSize;
private: System::Windows::Forms::Label^ HTsize;
private: System::Windows::Forms::Button^ LoadFile;
private: System::Windows::Forms::Button^ SaveFile;
private: HashTableForm^ hashTableForm;
protected:
protected:
private:
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
System::ComponentModel::Container^ components;
private: System::Windows::Forms::DataGridView^ dataGridView1;
private: System::Windows::Forms::TextBox^ textBoxVendorCode;
private: System::Windows::Forms::TextBox^ textBoxProductName;
private: System::Windows::Forms::TextBox^ textBoxTIN;
private: System::Windows::Forms::TextBox^ textBoxDay;
private: System::Windows::Forms::TextBox^ textBoxMonth;
private: System::Windows::Forms::TextBox^ textBoxYear;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Label^ label5;
private: System::Windows::Forms::Label^ label6;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ ProductName;
private: System::Windows::Forms::Button^ Search;
Tree* tree;
// Добавить данные о продукте в таблицу
String^ productName = gcnew String(node->key.c_str());
dataGridView1->Rows->Add(productName);
FillTable(node->right);
}
}
private: void PopulateTableFromTree()
{
// Очистить таблицу перед загрузкой новых данных
dataGridView1->Rows->Clear();
// Начать обход дерева с корня
FillTable(tree->root);
}
private: void UpdateTableAfterAddRemove()
{
// Обновить таблицу после добавления или удаления элемента из tree
PopulateTableFromTree();
}
private: System::Void btnAdd_Click(System::Object^ sender, System::EventArgs^ e) {
// Очистить таблицу перед загрузкой новых данных
dataGridView1->Rows->Clear();
long long int newVC;
long long int newTIN;
int newDay;
int newMonth;
int newYear;
if (Int64::TryParse(textBoxVendorCode->Text, newVC) && !System::String::IsNullOrWhiteSpace(textBoxProductName->Text) && Int64::TryParse(textBoxTIN->Text, newTIN) && Int32::TryParse(textBoxDay->Text, newDay) && Int32::TryParse(textBoxMonth->Text, newMonth) && Int32::TryParse(textBoxYear->Text, newYear))
{
if (VendorCode(newVC).correct && TIN(newTIN).correct && Date(newDay, newMonth, newYear).correct)
{
std::string newPN = msclr::interop::marshal_as<std::string>(textBoxProductName->Text);
tree->addItem(newVC, newPN, newTIN, newDay, newMonth, newYear);
UpdateTableAfterAddRemove();
}
}
UpdateTableAfterAddRemove();
}
private: System::Void btnRemove_Click(System::Object^ sender, System::EventArgs^ e) {
// Очистить таблицу перед загрузкой новых данных
dataGridView1->Rows->Clear();
// Получение значений из текстовых полей
std::string pn;
int d, m, y;
if (!System::String::IsNullOrWhiteSpace(textBoxProductName->Text) && Int32::TryParse(textBoxDay->Text, d) && Int32::TryParse(textBoxMonth->Text, m) && Int32::TryParse(textBoxYear->Text, y))
{
pn = msclr::interop::marshal_as<std::string>(textBoxProductName->Text);
// Удаление элемента
tree->removeItem(pn, d, m, y);
// Обновить таблицу после удаления элемента из дерева
UpdateTableAfterAddRemove();
}
}
private: System::Void textBoxHTSize_TextChanged(System::Object^ sender, System::EventArgs^ e) {
int newSize;
if (Int32::TryParse(textBoxHTSize->Text, newSize))
{
if (newSize >= 5)
{
if (tree->isEmpty())
tree->setHashTableSize(newSize);
else
MessageBox::Show("Tree is not empty.");
}
}
}
private: System::Void dataGridView1_CellClick(System::Object^ sender, System::Windows::Forms::DataGridViewCellEventArgs^ e)
{
if (hashTableForm != nullptr)
{
if (e->RowIndex >= 0 && e->ColumnIndex >= 0) // Проверяем, что нажата валидная ячейка
{
Object^ cellValue = dataGridView1->Rows[e->RowIndex]->Cells[e->ColumnIndex]->Value;
if (cellValue != nullptr && !String::IsNullOrEmpty(cellValue->ToString()))
{
String^ productName = dataGridView1->Rows[e->RowIndex]->Cells[0]->Value->ToString(); // Получаем название продукта
hashTableForm->FillHashTableTable(productName);
hashTableForm->Show(); // Показываем форму HashTableForm
}
}
}
}
private: System::Void SaveFile_Click(System::Object^ sender, System::EventArgs^ e) {
SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog(); // Создаем диалоговое окно для сохранения файла
saveFileDialog1->Filter = "Text Files | *.txt"; // Фильтр для файлов txt
saveFileDialog1->Title = "Save as Text File"; // Заголовок диалогового окна
if (saveFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK) // Если место сохранения выбрано
{
// Сохраняем данные из дерева в выбранный файл
std::string filename = msclr::interop::marshal_as<std::string>(saveFileDialog1->FileName);
tree->writeFile(filename);
MessageBox::Show("Model data saved successfully to " + saveFileDialog1->FileName, "Save Successful", MessageBoxButtons::OK, MessageBoxIcon::Information);
}
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK) // Если файл выбран
{
// Считываем выбранный файл и передаем данные в дерево tree
std::string filename = msclr::interop::marshal_as<std::string>(openFileDialog1->FileName);
tree->readFile(filename); // Передаем имя файла
// Обновляем таблицу после загрузки данных из файла
PopulateTableFromTree();
}
}
};
}
Код MyForm.cpp:
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThreadAttribute]
int main()
{
Application::SetCompatibleTextRenderingDefault(false);
Application::EnableVisualStyles();
KursovayaCLR::MyForm form;
Application::Run(% form);
}
Код HashTableForm.h:
#pragma once
#include <msclr/marshal_cppstd.h>
#include "Kursovaya.cpp"
namespace KursovayaCLR {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Сводка для HashTableForm
/// </summary>
public ref class HashTableForm : public System::Windows::Forms::Form
{
private:
Tree* treePointer;
public:
HashTableForm(Tree* tree) : treePointer(tree)
{
InitializeComponent();
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~HashTableForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::DataGridView^ dataGridView1;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ Hash;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ VendorCode;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ ProductName;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ TIN;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ Day;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ Month;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ Year;
protected:
private:
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
System::ComponentModel::Container ^components;
// Найти узел по имени продукта
std::string productNameStr = msclr::interop::marshal_as<std::string>(productName);
Node* targetNode = treePointer->findbyname(productNameStr, treePointer->root);
if (targetNode != nullptr) {
// Создание строк в DataGridView в количестве HTSize
for (int i = 0; i < targetNode->ht.getSize(); i++)
{
dataGridView1->Rows->Add(); // Создание строки в DataGridView
// Заполнение данных в строке i из хеш-таблицы targetNode->ht
dataGridView1->Rows[i]->Cells[0]->Value = i; // Хеш
if (targetNode->ht.table[i].flag == 1)
{
dataGridView1->Rows[i]->Cells[1]->Value = targetNode->ht.table[i].sorts.vendorcodes.vendorcode; // VendorCode
dataGridView1->Rows[i]->Cells[2]->Value = gcnew String(targetNode->ht.table[i].sorts.productnames.productname.c_str()); // ProductName
dataGridView1->Rows[i]->Cells[3]->Value = targetNode->ht.table[i].sorts.tins.tin; // TIN
dataGridView1->Rows[i]->Cells[4]->Value = targetNode->ht.table[i].sorts.dates.day; // Day
dataGridView1->Rows[i]->Cells[5]->Value = targetNode->ht.table[i].sorts.dates.month; // Month
dataGridView1->Rows[i]->Cells[6]->Value = targetNode->ht.table[i].sorts.dates.year; // Year
}
}
}
}
};
}
Измени метод private: System::Void Search_Click(System::Object^ sender, System::EventArgs^ e) так, чтобы:
Поиск осуществляется по наименованию товара и дате (как удаление)
Ячейка таблицы из MyForm.h, в которой найден первый ключ, подсвечивается зелёным
Открывается таблица HashTableForm.h с этим именем (как в dataGridView1_CellClick), и в ячейке, в которой найден второй ключ, подсвечивается зелёным
Важно: искать не по таблице интерфейса, а по структуре tree с помощью методов поиска из Kursovaya.cpp
На экран выводится сообщение с количеством шагов поиска
Сейчас он выглядит так:
private: System::Void Search_Click(System::Object^ sender, System::EventArgs^ e) {
// Очистить таблицу перед загрузкой новых данных
dataGridView1->Rows->Clear();
// Получить значения из текстовых полей
std::string pn;
int d, m, y;
if (!System::String::IsNullOrWhiteSpace(textBoxProductName->Text) && Int32::TryParse(textBoxDay->Text, d) && Int32::TryParse(textBoxMonth->Text, m) && Int32::TryParse(textBoxYear->Text, y))
{
pn = msclr::interop::marshal_asstd::string(textBoxProductName->Text);
// Поиск элемента
int searchSteps = tree->searchItem(pn, d, m, y);
// Обновить таблицу после поиска элемента в дереве
PopulateTableFromTree();
// Подсветить найденные ячейки
for (int i = 0; i < dataGridView1->Rows->Count; i++)
{
DataGridViewRow^ row = dataGridView1->Rows[i];
std::string productNameStr = msclr::interop::marshal_as<std::string>(row->Cells[0]->Value->ToString());
if (productNameStr == pn && Convert::ToInt32(row->Cells[4]->Value) == d && Convert::ToInt32(row->Cells[5]->Value) == m && Convert::ToInt32(row->Cells[6]->Value) == y)
{
row->Cells[0]->Style->BackColor = Color::Green; // Подсветить ячейку зеленым
break; // Выход из цикла после подсветки первой найденной ячейки
}
}
// Открыть форму HashTableForm и заполнить таблицу
if (searchSteps != -1)
{
// Показать форму HashTableForm с подсвеченной ячейкой
}
}
}
private: System::Void Search_Click(System::Object^ sender, System::EventArgs^ e) {
// Очистить таблицу перед загрузкой новых данных
dataGridView1->Rows->Clear();
// Получить значения из текстовых полей
std::string pn;
int d, m, y;
if (!System::String::IsNullOrWhiteSpace(textBoxProductName->Text) && Int32::TryParse(textBoxDay->Text, d) && Int32::TryParse(textBoxMonth->Text, m) && Int32::TryParse(textBoxYear->Text, y))
{
pn = msclr::interop::marshal_as<std::string>(textBoxProductName->Text);
// Поиск элемента
int searchSteps = tree->searchItem(pn, d, m, y);
// Обновить таблицу после поиска элемента в дереве
PopulateTableFromTree();
// Подсветить найденные ячейки
for (int i = 0; i < dataGridView1->Rows->Count; i++)
{
DataGridViewRow^ row = dataGridView1->Rows[i];
std::string productNameStr = msclr::interop::marshal_as<std::string>(row->Cells[0]->Value->ToString());
if (productNameStr == pn && Convert::ToInt32(row->Cells[4]->Value) == d && Convert::ToInt32(row->Cells[5]->Value) == m && Convert::ToInt32(row->Cells[6]->Value) == y)
{
row->Cells[0]->Style->BackColor = Color::Green; // Подсветить ячейку зеленым
break; // Выход из цикла после подсветки первой найденной ячейки
}
}
// Открыть форму HashTableForm и заполнить таблицу
if (searchSteps != -1)
{
// Найти узел с найденным продуктом
Node* parentNode = tree->findbyname(pn, tree->root);
if (parentNode != nullptr)
{
// Открываем и заполняем таблицу HashTableForm
HashTableForm^ hashTableForm = gcnew HashTableForm(tree);
hashTableForm->FillHashTableTable(pn);
hashTableForm->Show();
// Подсветить найденную ячейку в таблице HashTableForm
for (int i = 0; i < hashTableForm->dataGridView1->Rows->Count; i++)
{
DataGridViewRow^ row = hashTableForm->dataGridView1->Rows[i];
if (Convert::ToInt32(row->Cells[4]->Value) == d && Convert::ToInt32(row->Cells[5]->Value) == m && Convert::ToInt32(row->Cells[6]->Value) == y)
{
row->Cells[0]->Style->BackColor = Color::Green; // Подсветить ячейку зеленым
break; // Выход из цикла после подсветки найденной ячейки
}
}
}
}
else
{
MessageBox::Show("Product not found.", "Search Result", MessageBoxButtons::OK, MessageBoxIcon::Information);
}
// Вывод количества шагов поиска
MessageBox::Show("Search took " + searchSteps.ToString() + " steps.", "Search Steps", MessageBoxButtons::OK, MessageBoxIcon::Information);
}
else
{
MessageBox::Show("Invalid input. Please enter valid values for Product Name, Day, Month, and Year.", "Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
Для передачи строкового значения pn в функцию FillHashTableTable в классе HashTableForm, можно добавить дополнительное поле в класс HashTableForm для хранения этого значения и использовать его при вызове метода FillHashTableTable.
Первым шагом, внесем изменения в класс HashTableForm:
public:
String^ productNameToSearch; // поле для хранения имени продукта для поиска
// конструктор с инициализацией productNameToSearch
HashTableForm(Tree* tree, String^ productName) : treePointer(tree), productNameToSearch(productName)
{
InitializeComponent();
}
// метод для заполнения таблицы с учетом имени продукта из productNameToSearch
public: void FillHashTableTable()
{
dataGridView1->Rows->Clear();
std::string productNameStr = msclr::interop::marshal_as<std::string>(productNameToSearch);
// Найти узел по имени продукта
Node* targetNode = treePointer->findbyname(productNameStr, treePointer->root);
if (targetNode != nullptr) {
// Создание строк в DataGridView в количестве HTSize
for (int i = 0; i < targetNode->ht.getSize(); i++)
{
dataGridView1->Rows->Add(); // Создание строки в DataGridView
// Заполнение данных в строке i из хеш-таблицы targetNode->ht
dataGridView1->Rows[i]->Cells[0]->Value = i; // Хеш
if (targetNode->ht.table[i].flag == 1)
{
dataGridView1->Rows[i]->Cells[1]->Value = targetNode->ht.table[i].sorts.vendorcodes.vendorcode; // VendorCode
dataGridView1->Rows[i]->Cells[2]->Value = gcnew String(targetNode->ht.table[i].sorts.productnames.productname.c_str()); // ProductName
dataGridView1->Rows[i]->Cells[3]->Value = targetNode->ht.table[i].sorts.tins.tin; // TIN
dataGridView1->Rows[i]->Cells[4]->Value = targetNode->ht.table[i].sorts.dates.day; // Day
dataGridView1->Rows[i]->Cells[5]->Value = targetNode->ht.table[i].sorts.dates.month; // Month
dataGridView1->Rows[i]->Cells[6]->Value = targetNode->ht.table[i].sorts.dates.year; // Year
}
}
}
}
Далее, в методе Search_Click в классе MyForm:
private: System::Void Search_Click(System::Object^ sender, System::EventArgs^ e) {
// Очистить таблицу перед загрузкой новых данных
dataGridView1->Rows->Clear();
// Получить значения из текстовых полей
std::string pn;
int d, m, y;
if (!System::String::IsNullOrWhiteSpace(textBoxProductName->Text) && Int32::TryParse(textBoxDay->Text, d) && Int32::TryParse(textBoxMonth->Text, m) && Int32::TryParse(textBoxYear->Text, y))
{
pn = msclr::interop::marshal_as<std::string>(textBoxProductName->Text);
// Поиск элемента
int searchSteps = tree->searchItem(pn, d, m, y);
// Обновить таблицу после поиска элемента в дереве
PopulateTableFromTree();
// Подсветить найденные ячейки
for (int i = 0; i < dataGridView1->Rows->Count; i++)
{
DataGridViewRow^ row = dataGridView1->Rows[i];
std::string productNameStr = msclr::interop::marshal_as<std::string>(row->Cells[0]->Value->ToString());
if (productNameStr == pn && Convert::ToInt32(row->Cells[4]->Value) == d && Convert::ToInt32(row->Cells[5]->Value) == m && Convert::ToInt32(row->Cells[6]->Value) == y)
{
row->Cells[0]->Style->BackColor = Color::Green; // Подсветить ячейку зеленым
break; // Выход из цикла после подсветки первой найденной ячейки
}
}
// Открыть форму HashTableForm и заполнить таблицу
if (searchSteps != -1)
{
// Создать форму HashTableForm с указанием имени продукта для поиска
HashTableForm^ hashTableForm = gcnew HashTableForm(tree, textBoxProductName->Text);
hashTableForm->FillHashTableTable();
hashTableForm->Show();
}
else
{
MessageBox::Show("Product not found.", "Search Result", MessageBoxButtons::OK, MessageBoxIcon::Information);
}
// Вывод количества шагов поиска
MessageBox::Show("Search took " + searchSteps.ToString() + " steps.", "Search Steps", MessageBoxButtons::OK, MessageBoxIcon::Information);
}
else
{
MessageBox::Show("Invalid input. Please enter valid values for Product Name, Day, Month, and Year.", "Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
}
}
Теперь метод Search_Click правильно передает имя продукта в форму HashTableForm для операции поиска и подсвечивает найденные ячейки.