迭代器自增及算术运算是否会生成全新迭代器?
Great question—let’s break this down clearly, including the context from C++ Primer 5th Edition you referenced.
1. Does incrementing an iterator produce a new iterator?
This depends on whether you’re using pre-increment (++it) or post-increment (it++):
- Pre-increment (
++it): This modifies the original iterator to point to the next element, then returns a reference to the same iterator object. No new iterator is created here—you’re just working with the original instance. - Post-increment (
it++): This first creates a copy of the original iterator (pointing to its current position), then modifies the original iterator to point to the next element, and finally returns that copy. In this case, yes, the result is a brand-new iterator object.
Here’s a quick code example to illustrate:
#include <vector> #include <cassert> int main() { std::vector<int> vec = {1, 2, 3}; auto it = vec.begin(); // Pre-increment: returns a reference to the original iterator auto& pre_inc_result = ++it; assert(&pre_inc_result == &it); // They're the same object // Post-increment: returns a copy (new iterator) auto post_inc_result = it++; assert(&post_inc_result != &it); // Different objects return 0; }
2. Do iterator arithmetic operations create a brand-new iterator?
First, note that only random-access iterators (like those from std::vector, std::array, and pointers) support arithmetic operations (addition/subtraction of integers, subtraction of two iterators).
As you cited from C++ Primer:
当我们给指针加上(或减去)一个整数值时,结果是一个新指针,该新指针指向原指针前方(或后方)指定数量的元素;同时该书第118页指出指针属于Iterator(迭代器)。
Since pointers are a type of iterator, this behavior extends to all random-access iterators. When you perform arithmetic operations (e.g., it + 5, it - 2), the original iterator remains unchanged, and the result is a new iterator object pointing to the calculated position.
Example:
std::vector<int> vec = {10, 20, 30, 40, 50}; auto it = vec.begin(); // Create a new iterator via arithmetic; original remains unmodified auto it_plus_2 = it + 2; assert(it == vec.begin()); // Original still points to first element assert(it_plus_2 == vec.begin() + 2); // New iterator points to third element
So to sum up: For random-access iterators (including pointers), arithmetic operations do generate a completely new iterator, just like pointer arithmetic does.
内容的提问来源于stack exchange,提问作者SLN

