The difference between std :: vector :: front () and begin ()

vector help talks about front()

Returns a reference to the first element in a vector container. Unlike the vector::begin member, which returns an iterator to the same element, this function returns a direct link.

Vector help says begin()

Returns an iterator referring to the first element in a vector container. Note that unlike the vector::front member, which returns a reference to the first element,> this function returns a random access iterator.

And this code outputs:

 char arr[] = { 'A', 'B', 'C' }; vector<char> vec(arr, arr+sizeof(arr)); cout << "address of vec.front() " << (void*)&vec.front() << endl; cout << "address of vec.begin() " << (void*)&vec.begin() << endl; 

address vec.front() 00401F90 address vec.begin() 0030F494

I don’t understand what “direct link” means? In the case of begin() not random access iterator just a pointer ?

Can anyone point out the difference?

+4
source share
4 answers

In the case of begin () is not a random access iterator just a pointer?

No, the iterator has pointer semantics, but it's actually a class.

And even if that were the case, it should answer the question. He asks why the address of the pointer does not match the address of the object to which it points.

You will get the same value if you search for an iterator that will give you the first element:

 &(*vec.begin()) 

because

 *vec.begin() == vec.front() 
+8
source

According to Stroustrup in the C ++ programming language, section 16.3.3; think of front() as the first element and begin() as a pointer to the first element.

+11
source

For a vector, begin() and end() return random access iterators. They can return a simple pointer; this is good because it meets the requirements to become a random access iterator. In particular, you can write *begin() to get a reference to the first object in the sequence (if any). front() gives you a reference to the first object in the sequence without passing an intermediate iterator. Like this:

 vector<int> v; v.push_back(3); int i = *v.begin(); // i == 3 int j = v.front(); // j == 3 
+4
source

Assuming you have at least one element in a vector,

 vec.front() 

coincides with

 *vec.begin() 
+3
source

Source: https://habr.com/ru/post/1439172/


All Articles