give me a quick rundown on how to define and use lists in c++
- User
give me a quick rundown on how to define and use lists in c++
- Assistant
Here’s a lightning‐fast tour of std::list in C++ (a doubly‐linked list in the STL):
-
Include the header
#include <list> -
Declaration
std::list<int> L; // empty list of ints std::list<string> names{ "Alice", "Bob", "Carol" }; -
Basic operations
• push_back / push_frontL.push_back(10); L.push_front(5);• emplace_back / emplace_front (construct in-place)
names.emplace_back("Dave"); names.emplace_front("Zara");• size / empty
if (!L.empty()) std::cout << L.size();• access ends
int lo = L.front(); int hi = L.back(); -
Insertion & removal by iterator
auto it = L.begin(); std::advance(it, 1); // move iterator forward L.insert(it, 7); // insert 7 before position “it” it = L.erase(it); // erase element at “it”, returns next iterator -
Traversal
// Range‐based for (int x : L) std::cout << x << ' '; // Iterator‐based for (auto it = names.begin(); it != names.end(); ++it) std::cout << *it << '\n'; -
List‐specific algorithms (all run in O(n) or better per operation)
• sort(): L.sort();
• reverse(): L.reverse();
• unique(): L.unique(); // remove consecutive duplicates
• merge(other): L.merge(other); // merge two sorted lists
• splice(): move elements from one list to another in O(1)
— Example Putting It All Together:
#include <bits/stdc++.h> using namespace std; int main() { list<int> L = {1,2,3}; L.push_front(0); // 0,1,2,3 L.push_back(4); // 0,1,2,3,4 // Insert “100” before the 3 auto it = find(L.begin(), L.end(), 3); L.insert(it, 100); // 0,1,2,100,3,4 // Erase the 2 it = find(L.begin(), L.end(), 2); L.erase(it); // 0,1,100,3,4 // Sort and remove duplicates L.sort(); L.unique(); // Print for (int x : L) cout << x << ' '; cout << '\n'; }Notes:
- std::list is great when you need fast O(1) insert/erase in the middle via iterators.
- If you only push/pop at ends and need random access, prefer std::deque or std::vector.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.