Reputation: 1633
When I call sort
on a vector
of double
s using the begin()
and end()
iterators how does the sort
function modify the original vector
to contain the sorted values?
I though iterators simply represented a value, so how could they cause the original vector
to get modified?
vector<double> nums = {10.33, 20.44, 60.77};
sort(nums.begin(), nums.end(); // how does the original nums get changed?
Upvotes: 4
Views: 124
Reputation: 65630
An iterator doesn't represent the value, it represents some position in a container, stream, or stream buffer. Essentially, they are a generalization of pointers. Some iterators will let you modify what they are iterating over using indirection (*it
).
In the simplest case, it could simply be a pointer. Consider this code:
vector<double> nums = {10.33, 20.44, 60.77};
double* it = &nums[0]; //get the address of the first element
++it; //increment the pointer
*it = 42; //assign 42 to nums[1]
An iterator provides much the same functionality (depending on the type of iterator).
vector<double> nums = {10.33, 20.44, 60.77};
vector<double>::iterator it = nums.begin();//get an iterator to the first element
++it; //increment the iterator
*it = 42; //assign 42 to nums[1]
Upvotes: 4