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
Quick rundown – C++ “lists”
-
Header
#include <vector> // dynamic array #include <list> // doubly-linked list #include <forward_list> // singly-linked list -
vector (99 % of CP cases)
vector<int> a; // empty vector<int> b(5, 42); // {42,42,42,42,42} vector<int> c = {1,2,3}; // initializer-listCommon ops
a.push_back(x); // O(1) amortized a.pop_back(); // O(1) a[i] = 7; // random access a.size(); // #elements a.empty(); // bool a.clear(); // erase all sort(a.begin(), a.end());// <algorithm> -
list (doubly-linked)
list<int> L = {10, 20, 30}; L.push_front(5); // O(1) L.push_back(35); // O(1) L.pop_front(); // O(1) L.pop_back(); // O(1) auto it = L.begin(); ++it; L.insert(it, 99); // insert before iterator L.erase(it); // erase at iterator -
forward_list (singly-linked)
forward_list<int> fl = {1,2,3}; fl.push_front(0); // O(1) fl.pop_front(); // O(1) -
Range-for loop (works for all)
for (int x : a) cout << x << ' ';
That’s it—
vectoris your default; uselist/forward_listonly when you need constant-time insert/erase in the middle.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.