Answer the question
In order to leave comments, you need to log in
There are two functions that differ in comparison sign. How to "combine"?
There are two functions of 20 lines each. Let there be make_greater
and make_less
. They differ only by the comparison sign: in one ">", in the other "<". Can they be combined somehow? I write in C++.
Obviously, I can add one more argument and just compare it, they say, if mode == ">"
, then the corresponding one is executed. branch and vice versa.
I just heard about templates, and other solutions became interesting.
UPD:
void make_list_less(LinkedList *facelist, LinkedList *less, int pivot)
{
LinkedListItem *tmp, *ptmp;
tmp = facelist->first;
ptmp = tmp;
while(tmp) {
if(tmp->num <= pivot) { // <-------------------- "<="
AddLL(less, tmp->num);
if(tmp == facelist->first) {
facelist->first = ptmp->next;
if(tmp == facelist->last)
facelist->last = ptmp->next;
ptmp = tmp->next;
facelist->size = facelist->size - 1;
delete tmp;
tmp = ptmp;
continue;
}
ptmp->next = tmp->next;
facelist->size = facelist->size - 1;
delete tmp;
tmp = ptmp->next;
continue;
}
ptmp = tmp;
tmp = tmp->next;
}
}
void make_list_greater(LinkedList *facelist, LinkedList *greater, int pivot)
{
LinkedListItem *tmp, *ptmp;
tmp = facelist->first;
ptmp = tmp;
while(tmp) {
if(tmp->num > pivot) { // <-------------------- ">"
AddLL(greater, tmp->num);
if(tmp == facelist->first) {
facelist->first = ptmp->next;
if(tmp == facelist->last)
facelist->last = ptmp->next;
ptmp = tmp->next;
facelist->size = facelist->size - 1;
delete tmp;
tmp = ptmp;
continue;
}
ptmp->next = tmp->next;
facelist->size = facelist->size - 1;
delete tmp;
tmp = ptmp->next;
continue;
}
ptmp = tmp;
tmp = tmp->next;
}
}
int pivot
, the second, on the contrary, that is greater, thereby forming another list. Answer the question
In order to leave comments, you need to log in
You can pass a comparison function.
int DoSomething(int a, int b, bool compare(int a, int b)) {
if (compare(a, b)) return a;
else return b;
}
DoSomething(1, 3, [](int a, int b){return a < b;}); // 1
DoSomething(1, 3, [](int a, int b){return a > b;}); // 3
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question