C++ <list> remove function
removeis used in list toremove all elements equal to the specified valueis a function that is a highly efficient operation unique to linked lists.
removeis a member function of the container class, used to delete all elements in the linked list that equal the specified value.
In the list,removethe time complexity is O(n).
Word Definitions: removemeans "remove", i.e., delete all elements equal to the specified value.
Basic syntax and parameters
Syntax format
void remove(const T& value);
Parameter description
- Parameter:
value- the value of the element to delete
Function description
- Return Value:
void(No return value). - Effect: Delete all elements in the linked list that equal value.
Example
Example 1: Delete all elements equal to the specified value
Example
#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 2, 4, 2, 5};
std::cout << "Original: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Delete all elements equal to 2
numbers.remove(2);
std::cout << "After remove(2): ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 2, 4, 2, 5};
std::cout << "Original: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Delete all elements equal to 2
numbers.remove(2);
std::cout << "After remove(2): ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Expected running result:
原始: 1 2 3 2 4 2 5 remove(2) 后: 1 3 4 5
Example 2: Delete a string
Example
#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> words = {"apple", "banana", "apple", "cherry", "apple"};
std::cout << "Original: ";
for(const auto& w : words) std::cout << w << " ";
std::cout << std::endl;
words.remove("apple");
std::cout << "remove(\"apple\") After: ";
for(const auto& w : words) std::cout << w << " ";
std::cout << std::endl;
return 0;
}
#include <list>
#include <string>
int main() {
std::list<std::string> words = {"apple", "banana", "apple", "cherry", "apple"};
std::cout << "Original: ";
for(const auto& w : words) std::cout << w << " ";
std::cout << std::endl;
words.remove("apple");
std::cout << "remove(\"apple\") After: ";
for(const auto& w : words) std::cout << w << " ";
std::cout << std::endl;
return 0;
}
Expected running result:
原始: apple banana apple cherry apple
remove("apple") 后: banana cherry
other extensions