Say I have a list:
list<int> A { 1, 2, 3, 4};
and I do this:
A.remove(5);
What would be returned by this? When I create a simple program for this in Visual Studio, it runs without giving any errors, so I am assuming it is a legal statement.
However, what if I wanted to keep track of whether or not the element is removed, and print out that it has either been removed or the element does not exist?
For example, is there something like this:
if (A.remove(5) == true) {
cout << "Element has been removed" << endl;
} else {
cout << "Element does not exist" << endl;
}
that can be done without looping through the list and comparing 5 to every element if it exists before first calling the remove()
function?
It is perfectly legal to call list::remove()
for a value that does not exist in the list.
Prior to C++20, list::remove()
does not have a return value, so the only way to know if any elements are removed or not is to check the list's new size()
after calling remove()
, eg:
list<int> A { 1, 2, 3, 4};
size_t old_size = A.size();
A.remove(5);
if (A.size() < old_size) {
cout << "Element has been removed" << endl;
} else {
cout << "Element does not exist" << endl;
}
However, in C++20 onward, list::remove()
returns the number of elements removed, eg:
list<int> A { 1, 2, 3, 4};
if (A.remove(5) > 0) {
cout << "Element has been removed" << endl;
} else {
cout << "Element does not exist" << endl;
}
Either way, note that list::remove()
removes every element that matches the specified value, so it must iterate the entire list to look for all potential matches. If you want to remove only the 1st match, use std::find()
and list::erase()
instead, eg:
list<int> A { 1, 2, 3, 4};
auto iter = find(A.begin(), A.end(), 5);
if (iter != A.end()) {
A.erase(iter);
cout << "Element has been removed" << endl;
} else {
cout << "Element does not exist" << endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With