C ++ vector iterators versus pointers

There are so many alternative ways to access the elements of a vector.

I could use a pointer like this:

vector<int> v = {10, 11, 12};
int *p = &v[0];
cout << *p;    //Outputs "10"

I could use a pointer too:

vector<int> v = {10, 11, 12};
vector<int>::pointer p = v.data();
cout << *p;    //Outputs "10"

I could also use an iterator type:

vector<int> v = {10, 11, 12};
vector<int>::iterator i = v.begin();
cout << *i;    //Outputs "10"

Are there any significant differences that I'm missing here?

+12
source share
4 answers

, . , , , vector. , vector<int>::iterator, , .

int* , p, , int. p , , . vector<int>::pointer - , , . , vector.

, vector<int>::iterator , . , vector<int>.

, , , - . , , std::list, , . iterator , .


, , - :

ForwardIteratorOf<int> it = std::begin(v);

ForwardIteratorOf<int> (, , ), , it. , ForwardIterator ( BidirectionalIterator, RandomAccessIterator - ).

+6

:

if ( !v.empty() )

, , .

vector, :

vector<int>::iterator i = v.begin();

, , .

if ( i != v.end() )
{
   // Do stuff.
}
+1

, . ( undefined), .

0

All are functionally the same in case you provided. For ease of reading the code, the iterator makes it more clear that the operation is performed on the vector. However, there are some nuances, especially when it comes to constant objects.

For instance,

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    const int a[5] = {1, 2, 30, 45, 500};
    auto it = begin(a);
    it++;
    int i = *it;
    i++;
    cout << i << endl;
} // Prints 3.

On the other hand, (excluding headers so as not to clutter up the screen)

int main() {
    const int a[5] = {1, 2, 30, 45, 500};
    int *p = a;
    cout << *p << endl;
}

It will not will not compile.

0
source

All Articles