C++ - List Part 4: Advanced List Operations
Lists offer several advanced methods for managing elements and optimizing storage.
Examples and Explanation
Merging Two Lists
std::list<int> list1 = {1, 3, 5};
std::list<int> list2 = {2, 4, 6};
list1.merge(list2); // Merges list2 into list1
Explanation: The merge() method combines two sorted lists into one.
Sorting a List
myList.sort(); // Sorts in ascending order
Explanation: Use the sort() method to sort elements. This is particularly useful as lists do not support random access.
Removing Duplicates
myList.unique();
Explanation: The unique() method removes consecutive duplicate elements.
Reversing a List
myList.reverse();
Explanation: The reverse() method reverses the order of elements in the list.