c++ list
时间: 2025-04-22 14:59:24 浏览: 17
### C++ STL List Usage and Examples
In the context of C++, `std::list` is a container that supports constant time insertions and deletions from anywhere within the sequence. This makes it particularly useful when frequent insertion or deletion operations are required.
#### Declaration and Initialization
A list can be declared using different methods:
```cpp
#include <iostream>
#include <list>
int main() {
std::list<int> my_list = {1, 2, 3}; // Initialize with values
// Add elements to the end of the list
my_list.push_back(4);
// Print all elements in the list
for (auto& elem : my_list) {
std::cout << elem << " ";
}
}
```
#### Common Operations on Lists
Adding an element at any position involves specifying where exactly one wants to add this new item:
```cpp
// Inserting before specific iterator location
my_list.insert(my_list.begin(), 0); // Inserts '0' as first element
```
Removing items also has multiple options available depending upon what needs removal – either by value or through iterators pointing towards those positions which need erasing:
```cpp
// Remove all occurrences of a particular value
my_list.remove(2);
// Erase single occurrence pointed by iterator
auto pos = my_list.begin();
pos++; // Move past beginning
my_list.erase(pos);
```
Checking whether two lists contain identical sequences without considering their order might involve sorting both collections beforehand followed by comparison via equality operator (`==`) provided they support such operation directly out-of-the-box like so:
```cpp
if (sorted_copy_of_my_list == another_sorted_list) {
// Both have same contents regardless of original ordering.
}
```
For more advanced manipulations including merging sorted ranges into destination containers while preserving relative orders among equal keys during merge process etc., refer standard library documentation regarding algorithms operating over bidirectional iterators since these apply equally well here too due to nature how linked structures internally manage memory allocation/deallocation patterns under hood[^1].
阅读全文
相关推荐



















