If I have array of pointers will it be the same? For example int **data
You'll need to adjust begin and end to return a type which works as an iterator. Which could be int* const* or int** for const and non-const my_array values respectively.
Note that there is a problem with the element deletion example.
1 2 3 4 5 6 7 8
// Deleting a element using iterators
for (i = v.begin(); i != v.end(); ++i) {
if (i == v.begin() + 1) {
i = v.erase(i);
// i now points to the element after the
// deleted element
}
}
As the comment correctly states, after the .erase() i points to the element after the deleted element - which is what is needed to be compared with .end() for correct termination. But i is incremented in the for loop so now points one element past the element following the deletion. It 'works' in this example as there are following entries. But if the deleted element was the last element then i will be one past .end() so the for comparison test will never succeed to give an infinite loop.
A 'better' solution could be:
1 2 3 4 5 6
// Deleting an element using iterators
for (auto i = v.begin(); i != v.end(); )
if (i == v.begin() + 1) // test for deletion of element
i = v.erase(i); // i now points to the element after the deleted element
else
++i;
where i is only incremented if the deletion test fails.
v.erase(v.begin()+1);
your code would remove all elements except the first (not just an element), would be similar to v.erase(v.begin()+1, v.end()); provided that the vector does hold enough elements.
the examples are awful, it's quite idiotic to use a loop there.
True. I didn't study the original example carefully enough! I just saw that i was incremented after the .erase() which is usually not what is required - as the deletion test is usually on a value not a position. Ouch!!!
My suggestion would have been better for say removing all elements that had the value 2
1 2 3 4 5 6
// Deleting an element using iterators
for (auto i = v.begin(); i != v.end(); )
if (*i == 2) // test for deletion of element
i = v.erase(i); // i now points to the element after the deleted element
else
++i;
I agree that the examples are awful and possibly hinder understanding rather than helping.
for (auto i = v.begin(); i != v.end(); )
if (*i == 2) // test for deletion of element
i = v.erase(i); // i now points to the element after the deleted element
else
++i;
This code requires quadratic time and therefore represents a serious performance bug.
Instead, use v.erase(std::remove(std::begin(v), std::end(v), 2), std::end(v));
Which requires linear time.