Explain why in C if x is an iterator for a vector v that has

Explain why in C++, if x is an iterator for a vector v that has both prefix ++ and the postfix ++,

that it it better to write

for (x=v.begin(); x < v.end(); ++x) { ... }

than to write:

for (x=v.begin(); x < v.end(); x++) { ... }

Solution

The preincrement is a little(very little infact) better efficient than post increment. This is because, when pre-incrementing, the iterator will be incremented, and the new value will be used further, but in the case of post-incrementing, the old value will be copied, and will be used for that loop value, and at the end, the new value will be utilized further.

As, the copy and swapping has to be done in post-increment it takes a little amount of time.

Explain why in C++, if x is an iterator for a vector v that has both prefix ++ and the postfix ++, that it it better to write for (x=v.begin(); x < v.end();

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site