Skip to content
TheChatArchiveThe Chat Archive
o4-mini-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

give me a quick rundown on how to define and use lists in c++

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Kimikimi-k2-0711-preview’s answer.
  1. User

    give me a quick rundown on how to define and use lists in c++

  2. Assistant

    Here’s a lightning‐fast tour of std::list in C++ (a doubly‐linked list in the STL):

    1. Include the header

      #include <list>
      
    2. Declaration

      std::list<int>   L;          // empty list of ints
      std::list<string> names{ "Alice", "Bob", "Carol" };
      
    3. Basic operations
      • push_back / push_front

      L.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();
      
    4. 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
      
    5. 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';
      
    6. 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.