简体   繁体   中英

c++ iterator vs pointer for vector access

For a vector I can use both an iterator and a pointer to access its elements and iterate through them, for example:

std::vector<int> x {0, 1, 2};
std::vector<int>::iterator it = x.begin();
int *begin = &x[0];

Both the iterator and the pointer would give access to the same object. However, as far as I know, the preferred way is to use iterators (for any containers other than arrays). Is there a particular reason for this? (Other than the fact that in my creation of begin I assume the container has a [ ] operation defined.)

Use iterators unless you have a specific reason to do otherwise. Several important operations (eg insert , erase , etc.) require iterators, so you'll often need to cough one up anyway. Iterators also work really nicely with algorithms to accomplish things that are complex of awkward to do with explicit loops. Plus, they're generic enough to work for all containers, not just vector and string .

Of course if you're in a situation which does require a pointer (eg interacting with a C API, or interacting across a module boundary) you shouldn't feel "dirty" about doing that either -- pointers are fine. Just use them where necessary.

Finally, in the specific case of vector and string, be sure to consider indices. Some algorithms are more readable using them and they have the advantage that they are never invalidated if the vector is forced to reallocate or something like that. (Just note that this locks you into vector or string and can make changing containers later difficult)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM