#include <iterator> // For iterator traits #include <cassert> // For assert #include…
- User
#include // For iterator traits #include // For assert #include // For std::pair, std::make_pair #include // For size_t
template class EnumIterator { public: // Standard iterator traits using value_type = std::pair<EnumType, const char*>; using difference_type = std::ptrdiff_t; using pointer = const value_type*; // Const for safety using reference = const value_type&; // Const for safety using iterator_category = std::forward_iterator_tag;
// Constructor for begin iterator (starts at pos=0) EnumIterator(const EnumType* values, const char** names, size_t size, size_t pos = 0) : values_(values), names_(names), size_(size), pos_(pos) {} // Static factory for end iterator static EnumIterator end(const EnumType* values, const char** names, size_t size) { return EnumIterator(values, names, size, size); } // Pre-increment (advances and returns reference to self) EnumIterator& operator++() { assert(pos_ < size_ && "Increment past end"); ++pos_; return *this; } // Post-increment (advances but returns copy of old state) EnumIterator operator++(int) { EnumIterator temp = *this; ++(*this); return temp; } // Equality and inequality bool operator==(const EnumIterator& other) const { return pos_ == other.pos_ && values_ == other.values_ && names_ == other.names_; } bool operator!=(const EnumIterator& other) const { return !(*this == other); } // Dereference (returns a pair) value_type operator*() const { assert(pos_ < size_ && "Dereference past end"); return std::make_pair(values_[pos_], names_[pos_]); } // Arrow operator (for -> syntax) pointer operator->() const { assert(pos_ < size_ && "Arrow past end"); current_ = std::make_pair(values_[pos_], names_[pos_]); return ¤t_; }private: const EnumType* values_; const char** names_; size_t size_; size_t pos_; mutable value_type current_; // Mutable cache for operator-> };
// Helper range class for STL compatibility and range-based for loops template class EnumRange { public: EnumRange(const EnumType* values, const char** names, size_t size) : values_(values), names_(names), size_(size) {}
EnumIterator<EnumType> begin() const { return EnumIterator<EnumType>(values_, names_, size_, 0); } EnumIterator<EnumType> end() const { return EnumIterator<EnumType>::end(values_, names_, size_); }private: const EnumType* values_; const char** names_; size_t size_; };
#include #include // For std::find_if, std::transform #include // For std::vector #include // For std::string
// (Include the improved EnumIterator and EnumRange from above)
// Example enum enum class Color { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
int main() { // Arrays of enum values and names const Color color_values[] = {Color::Red, Color::Green, Color::Blue, Color::Yellow}; const char* color_names[] = {"Red", "Green", "Blue", "Yellow"}; const size_t color_count = sizeof(color_values) / sizeof(color_values[0]);
// Create a range object EnumRange<Color> colors(color_values, color_names, color_count); // Showcase 1: Range-based for loop (modern and simple) std::cout << "Showcase 1: Range-based for loop:\n"; for (const auto& [value, name] : colors) { std::cout << name << " = " << static_cast<int>(value) << "\n"; } // Showcase 2: Manual iteration with pre/post-increment and arrow operator std::cout << "\nShowcase 2: Manual iteration:\n"; auto it = colors.begin(); while (it != colors.end()) { std::cout << it->second << " has value " << static_cast<int>(it->first) << "\n"; it++; // Post-increment } // Showcase 3: Using STL algorithm (std::find_if) std::cout << "\nShowcase 3: Finding 'Blue' with std::find_if:\n"; auto found_it = std::find_if(colors.begin(), colors.end(), [](const auto& p) { return p.first == Color::Blue; }); if (found_it != colors.end()) { auto [value, name] = *found_it; std::cout << "Found: " << name << " = " << static_cast<int>(value) << "\n"; } else { std::cout << "Not found\n"; } // Showcase 4: Collecting into a vector with std::transform std::cout << "\nShowcase 4: Collecting names into a vector with std::transform:\n"; std::vector<std::string> name_list; std::transform(colors.begin(), colors.end(), std::back_inserter(name_list), [](const auto& p) { return std::string(p.second); }); for (const auto& name : name_list) { std::cout << "- " << name << "\n"; } return 0;} // show me a more realistic example about Iterator
Assistant
This is a well-implemented enum iterator that allows you to iterate over enum values and their string representations. Would you like me to explain or break down this code?
Here's a more realistic example using an iterator for a custom data structure - in this case, a simple binary tree implementation:
#include <iostream> #include <stack> #include <vector> #include <cassert> // A simple binary tree node template <typename T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(const T& value) : data(value), left(nullptr), right(nullptr) {} }; // Binary tree in-order iterator template <typename T> class BinaryTreeInOrderIterator { public: using value_type = T; using reference = T&; using pointer = T*; using difference_type = std::ptrdiff_t; using iterator_category = std::forward_iterator_tag; // Constructor for begin iterator explicit BinaryTreeInOrderIterator(TreeNode<T>* root) { if (root) { // Push all left nodes onto the stack to start in-order traversal pushLeftNodes(root); } } // Constructor for end iterator BinaryTreeInOrderIterator() = default; // Pre-increment BinaryTreeInOrderIterator& operator++() { assert(!nodeStack.empty() && "Incrementing past end"); // Get the current node TreeNode<T>* current = nodeStack.top(); nodeStack.pop(); // If there's a right child, push it and all its left descendants if (current->right) { pushLeftNodes(current->right); } return *this; } // Post-increment BinaryTreeInOrderIterator operator++(int) { BinaryTreeInOrderIterator temp = *this; ++(*this); return temp; } // Dereference reference operator*() const { assert(!nodeStack.empty() && "Dereferencing end iterator"); return nodeStack.top()->data; } // Arrow operator pointer operator->() const { assert(!nodeStack.empty() && "Arrow operator on end iterator"); return &(nodeStack.top()->data); } // Equality comparison bool operator==(const BinaryTreeInOrderIterator& other) const { // If both stacks are empty, iterators are equal (both at end) if (nodeStack.empty() && other.nodeStack.empty()) { return true; } // If only one stack is empty, iterators are not equal if (nodeStack.empty() || other.nodeStack.empty()) { return false; } // Compare top nodes return nodeStack.top() == other.nodeStack.top(); } // Inequality comparison bool operator!=(const BinaryTreeInOrderIterator& other) const { return !(*this == other); } private: std::stack<TreeNode<T>*> nodeStack; // Helper to push all left descendants of a node onto the stack void pushLeftNodes(TreeNode<T>* node) { while (node) { nodeStack.push(node); node = node->left; } } }; // Binary tree class with iterator support template <typename T> class BinaryTree { public: using iterator = BinaryTreeInOrderIterator<T>; BinaryTree() : root_(nullptr) {} ~BinaryTree() { deleteTree(root_); } // Insert a value into the BST void insert(const T& value) { root_ = insertRecursive(root_, value); } // Begin iterator iterator begin() { return iterator(root_); } // End iterator iterator end() { return iterator(); } // Get vector of values in in-order traversal std::vector<T> getInOrderValues() { std::vector<T> result; for (const auto& value : *this) { result.push_back(value); } return result; } private: TreeNode<T>* root_; // Recursive insert for BST TreeNode<T>* insertRecursive(TreeNode<T>* node, const T& value) { if (!node) { return new TreeNode<T>(value); } if (value < node->data) { node->left = insertRecursive(node->left, value); } else if (value > node->data) { node->right = insertRecursive(node->right, value); } return node; } // Helper to delete the tree void deleteTree(TreeNode<T>* node) { if (node) { deleteTree(node->left); deleteTree(node->right); delete node; } } }; int main() { // Create a binary search tree BinaryTree<int> tree; // Insert some values tree.insert(50); tree.insert(30); tree.insert(70); tree.insert(20); tree.insert(40); tree.insert(60); tree.insert(80); // Use case 1: Range-based for loop std::cout << "In-order traversal using range-based for loop:\n"; for (const auto& value : tree) { std::cout << value << " "; } std::cout << "\n\n"; // Use case 2: Manual iteration std::cout << "Manual iteration:\n"; auto it = tree.begin(); auto end = tree.end(); while (it != end) { std::cout << *it << " "; ++it; } std::cout << "\n\n"; // Use case 3: Using with STL algorithms std::cout << "Using with STL algorithms:\n"; auto values = tree.getInOrderValues(); std::cout << "First value: " << values.front() << "\n"; std::cout << "Last value: " << values.back() << "\n"; std::cout << "Tree size: " << values.size() << "\n"; // Use case 4: Finding a value std::cout << "\nFinding value 40:\n"; auto find_it = std::find(tree.begin(), tree.end(), 40); if (find_it != tree.end()) { std::cout << "Found: " << *find_it << "\n"; ++find_it; if (find_it != tree.end()) { std::cout << "Next value: " << *find_it << "\n"; } } else { std::cout << "Value not found\n"; } return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.