I need to somehow remove an element in a list if it is already in another list. I created a function but it doesn't work. Tell me how to fix it. thank you very much.
void compare(forward_list<string> list_1, forward_list<string> list_2) {
auto prev = list_1.before_begin();
for (int i = 0; i < Size(list_1); i++) {
auto l_front = list_1.begin();
advance(l_front, i);
for (int j = 0; j < Size(list_2); j++) {
auto l_front_2 = list_2.begin();
advance(l_front_2, j);
if (*l_front == *l_front_2)
{
l_front_2 = list_2.erase_after(l_front);
}
}
}
}
It seems you are trying to remove elements from
list_2
that are found inlist_1
. But in this statementyou are using the iterator
l_front
fromlist_1
that does not make a sense.Also if an element in
list_2
is removed then due to the expressionj++
in the for loopthe next element in the list will be skipped.
A straightforward approach can look for example the following way as it is shown in the demonstration program below.
The program output is
A much more simple function definition can be if to use the method
remove_if
or the general functionstd::erase_if
introduced in the C++ 20 Standard. For exampleOr if the compiler supports C++ 20 then
The both presented functions remove elements in
list_1
that are found inlist_2
.