通过让用户输入数字来过滤链表



我想根据类别筛选我的链表。我设法做到了,但我想改进它,让用户使用数字过滤,而不是键入类别。基本上,我将通过遍历链表一次来输出可用的类别,并且该类别将沿着一个数字输出。用户输入一个数字来选择类别,而不是输入类别本身。

void categoryFilter() {
int n = 1;
// Function to remove duplicates from a sorted list
ProductInventory* previous = nullptr;
ProductInventory* current;
// take an empty set to store linked list nodes for future reference
unordered_set<string> set;
// do till the linked list is empty
if (head != NULL) {
current = head;
while (current != nullptr)
{
previous = current;
// if the current node is seen before, ignore it
if (set.find(current->product_category) != set.end()) {
//previous = current;
previous->next = current->next;
}
else {
// insert the current node into the set and proceed to the next node
// 
set.insert(current->product_category);
//previous = current;
//cout <<n << ". "<< current->product_category<<endl;

//n = n + 1;
}
current = previous->next;
}

}
for (auto it = set.begin(); it !=
set.end(); ++it) {
cout << n << ". " << *it << endl;
n = n + 1;
}

}
void categoryFilter2() {
categoryFilter();
string category;
cin >> category;
if (head != NULL) {
ProductInventory* current = head;
//do while
while (current != NULL) {
if (category == current->product_category) {
cout << "1. Product Id: " << current->product_id;
cout << "2. Product Name: " << current->product_name;
cout << "3. Product Price: " << current->product_price;
cout << "4. Product Quantity: " << current->product_quantity;
cout << "5. Product Category: " << current->product_category;
}
current = current->next;
}

}
else {
cout << "No record in the list" << endl;
}
}

因为您在创建unordered_set之后打印产品列表,所以只要您不使其无效(即不从集合中插入或删除元素(,订单将是相同的。

您可以使用用户输入的n来迭代set

注意:在这种情况下,我更喜欢vector而不是unordered_set。由于您的链接列表是按排序的,vector将保持其顺序,并且使用用户将提供的索引来访问它是有效的

示例:

std::vector<std::string> categoryFilter() {
// Function to remove duplicates from a sorted list
ProductInventory* previous = nullptr;
ProductInventory* current;
// take an empty vec to store linked list nodes for future reference
std::vector<std::string> vec{};
// do till the linked list is empty
if (head != NULL) {
current = head;
while (current != nullptr) {
previous = current;
// if the current node is seen before, ignore it
if (std::find(vec.begin(), vec.end(), current->product_category) !=
vec.end()) {
// previous = current;
previous->next = current->next;
} else {
// insert the current node into the set and proceed to the next node
vec.push_back(current->product_category);
}
current = previous->next;
}
}
// note that your index is 1-based
int n = 1;
for (const auto& v : vec) {
std::cout << n << ". " << v << std::endl;
n++;
}
return vec;
}

用法:


auto category_vec = categoryFilter();
int n{};
std::cin >> n;
// change n to 0 based index
n=n-1;
// check for range 
//...
auto category = category_list[n];

相关内容

  • 没有找到相关文章